var current_params = {};
var selected = {};
var inputs = {};
var path = "";
var program = null;
var updating = false;
var counter_params = undefined;
var loaded = false;
var total = undefined;

var bodies_slugs = [];
var engine_fuels_slugs = [];
var used = false;

function formCatalogFilter(p, pr, props, u)
{
//	console.log("FILTER", "program", pr);
	path = p;
	selected = props;
	current_params = props;
	program = pr;
	used = u;

	$(".filter_header .tabs .tab").on("click", function()
	{
		var type = $(this).data("type");
		$(".filter_header .tabs .tab").removeClass("active");
		$(this).addClass("active");

		used = type === "used" ? true : false;
		if(used)
		{
			path = "/used/";
			$(".catalog_filter_new").css("display", "none");
			$(".catalog_filter_used").css("display", "block");
			updateCounter([], true);
		}
		else
		{
			path = "/catalog/";
			$(".catalog_filter_new").css("display", "block");
			$(".catalog_filter_used").css("display", "none");
			updateCounter([], true);
		}
	});
}

function updateCounter(parameters, reset = false)
{
	$(".catalog_filter_select").attr("disabled", true);

//	console.log("updateCounter", "parameters (selected)", parameters);

	if(!updating)
	{
		updating = true;

		$(".catalog_filter_spinner").show();
		$(".catalog_filter_search_button_counter").html("&nbsp;");
		//$(".catalog_filter_search_button_counter").hide();

		var params = {};
		if(program !== null)
		{
			params['PROGRAM'] = program;
		}

		for(let i in parameters)
		{
			if(parameters[i] !== undefined) { params[i] = parameters[i]; }
		}

		counter_params = params;

		if(used)
		{
			counter_params.USED = true;
		}

		setTimeout(function()
		{
			$.get("/api/catalog/parameters/", counter_params, function(response)
			{
				$(".catalog_filter_select").attr("disabled", false);

				if(response.brands !== undefined)
				{
					if(response.brands.length > 0)
					{
						var current = $(used ? ".filter_brands_used" : ".filter_brands").val();

						$(used ? ".filter_brands_used" : ".filter_brands").empty();
						$(used ? "#small_filter_brands_used" : "#small_filter_brands").empty();

						if(!reset && current !== "" && current !== null)
						{
							$(used ? ".filter_brands_used" : ".filter_brands").append('<option value="">Любая</option>');
							$(used ? "#small_filter_brands_used" : "#small_filter_brands").append('<option value="">Любая</option>');
						}
						else
						{
							$(used ? ".filter_brands_used" : ".filter_brands").append('<option value="" disabled="" selected="">Марка</option>');
							$(used ? "#small_filter_brands_used" : "#small_filter_brands").append('<option value="" disabled="" selected="">Марка</option>');
						}

						for(let i in response.brands)
						{
							var brand = response.brands[i];
							$(used ? ".filter_brands_used" : ".filter_brands").append('<option value="'+brand.value+'" data-id="'+brand.id+'" data-uid="'+brand.uid+'">'+brand.text+'</option>');
							$(used ? "#small_filter_brands_used" : "#small_filter_brands").append('<option value="'+brand.value+'" data-id="'+brand.id+'" data-uid="'+brand.uid+'">'+brand.text+'</option>');
						}

						$(used ? ".filter_brands_used" : ".filter_brands").val(reset ? "" : current);
						$(used ? "#small_filter_brands_used" : "#small_filter_brands").val(reset ? "" : current);
					}
				}

				if(response.models !== undefined)
				{
					var current = $(used ? ".filter_models_used" : ".filter_models").val();

					$(used ? ".filter_models_used" : ".filter_models").empty();
					$(used ? "#small_filter_models_used" : "#small_filter_models").empty();

					if(!reset && current !== "" && current !== null)
					{
						$(used ? ".filter_models_used" : ".filter_models").append('<option value="">Любая</option>');
						$(used ? "#small_filter_models_used" : "#small_filter_models").append('<option value="">Любая</option>');
					}
					else
					{
						$(used ? ".filter_models_used" : ".filter_models").append('<option value="" disabled="" selected="">Модель</option>');
						$(used ? "#small_filter_models_used" : "#small_filter_models").append('<option value="" disabled="" selected="">Модель</option>');
					}

					for(let i in response.models)
					{
						var model = response.models[i];
						$(used ? ".filter_models_used" : ".filter_models").append('<option value="'+model.value+'" data-id="'+model.id+'" data-uid="'+model.uid+'">'+model.text+'</option>');
						$(used ? "#small_filter_models_used" : "#small_filter_models").append('<option value="'+model.value+'" data-id="'+model.id+'" data-uid="'+model.uid+'">'+model.text+'</option>');
					}

					$(used ? ".filter_models_used" : ".filter_models").val(reset ? "" : current);
					$(used ? "#small_filter_models_used" : "#small_filter_models").val(reset ? "" : current);
				}

				if(response.modifications !== undefined)
				{
					var current = $(".filter_modifications").val();

					$(".filter_modifications").empty();

					if(!reset && current !== "" && current !== null)
					{
						$(".filter_modifications").append('<option value="">Любая</option>');
					}
					else
					{
						$(".filter_modifications").append('<option value="" disabled="" selected="">Модификация</option>');
					}

					for(let i in response.modifications)
					{
						var modification = response.modifications[i];
						$(".filter_modifications").append('<option value="'+modification.id+'">'+modification.text+'</option>');
					}

					$(".filter_modifications").val(reset ? "" : current);
				}

				if(response.bodies !== undefined)
				{
					if(response.bodies.length > 0)
					{
						bodies_slugs = response.bodies_slugs;

						var current = $(".filter_bodies").val();
						$(".filter_bodies").empty();

						if(!reset && current !== "" && current !== null)
						{
							$(".filter_bodies").append('<option value="">Любой</option>');
						}
						else
						{
							$(".filter_bodies").append('<option value="" disabled="" selected="">Кузов</option>');
						}

						for(let i in response.bodies)
						{
							$(".filter_bodies").append('<option value="'+response.bodies[i]+'">'+response.bodies[i]+'</option>');
						}

						if(!loaded)
						{
							if(selected['BODY'] !== undefined && selected['BODY'] !== null && selected['BODY'] !== "")
							{
								$(".filter_bodies").val(selected['BODY']);
								$(".filter_bodies").find("option").first().text("Любой").attr("disabled", false);
							}
						}
						else
						{
							$(".filter_bodies").val(reset ? "" : current);
						}
					}
				}

				if(response.gears !== undefined)
				{
					if(response.gears.length > 0)
					{
						var current = $(".filter_gears").val();
						$(".filter_gears").empty();

						if(!reset && current !== "" && current !== null)
						{
							$(".filter_gears").append('<option value="">Любая</option>');
						}
						else
						{
							$(".filter_gears").append('<option value="" disabled="" selected="">Коробка</option>');
						}

						for(let i in response.gears)
						{
							$(".filter_gears").append('<option value="'+response.gears[i]+'">'+response.gears[i]+'</option>');
						}

						if(!loaded)
						{
							if(selected['GEAR'] !== undefined && selected['GEAR'] !== null && selected['GEAR'] !== "")
							{
								$(".filter_gears").val(selected['GEAR']);
								$(".filter_gears").find("option").first().text("Любая").attr("disabled", false);
							}
						}
						else
						{
							$(".filter_gears").val(reset ? "" : current);
						}
					}
				}

				if(response.engine_fuels !== undefined)
				{
					if(response.engine_fuels.length > 0)
					{
						engine_fuels_slugs = response.engine_fuels_slugs;
						var current = $(".filter_engine_fuels").val();
						$(".filter_engine_fuels").empty();

						if(!reset && current !== "" && current !== null)
						{
							$(".filter_engine_fuels").append('<option value="">Любой</option>');
						}
						else
						{
							$(".filter_engine_fuels").append('<option value="" disabled="" selected="">Двигатель</option>');
						}

						for(let i in response.engine_fuels)
						{
							$(".filter_engine_fuels").append('<option value="'+response.engine_fuels[i]+'">'+response.engine_fuels[i]+'</option>');
						}

						if(!loaded)
						{
							if(selected['ENGINE_FUEL'] !== undefined && selected['ENGINE_FUEL'] !== null && selected['ENGINE_FUEL'] !== "")
							{
								$(".filter_engine_fuels").val(selected['ENGINE_FUEL']);
								$(".filter_engine_fuels").find("option").first().text("Любой").attr("disabled", false);
							}
						}
						else
						{
							$(".filter_engine_fuels").val(reset ? "" : current);
						}
					}
				}

				if(response.drives !== undefined)
				{
					if(response.drives.length > 0)
					{
						var current = $(".filter_drives").val();
						$(".filter_drives").empty();

						if(!reset && current !== "" && current !== null)
						{
							$(".filter_drives").append('<option value="">Любой</option>');
						}
						else
						{
							$(".filter_drives").append('<option value="" disabled="" selected="">Привод</option>');
						}

						for(let i in response.drives)
						{
							$(".filter_drives").append('<option value="'+response.drives[i]+'">'+response.drives[i]+'</option>');
						}

						if(!loaded)
						{
							if(selected['DRIVE'] !== undefined && selected['DRIVE'] !== null && selected['DRIVE'] !== "")
							{
								$(".filter_drives").val(selected['DRIVE']);
								$(".filter_drives").find("option").first().text("Любой").attr("disabled", false);
							}
						}
						else
						{
							$(".filter_drives").val(reset ? "" : current);
						}
					}
				}

				if(response.engine_volumes !== undefined)
				{
					if(response.engine_volumes.length > 0)
					{
						var current_from = parameters['ENGINE_VOLUME_FROM'] !== undefined ? parameters['ENGINE_VOLUME_FROM'] : "";
						var current_to = parameters['ENGINE_VOLUME_TO'] !== undefined ? parameters['ENGINE_VOLUME_TO'] : "";

						$(".filter_engine_volume_from").empty();
						$(".filter_engine_volume_to").empty();

						if(!reset && current_from !== "" && current_from !== null)
						{
							$(".filter_engine_volume_from").append('<option value="">Любой</option>');
						}
						else
						{
							$(".filter_engine_volume_from").append('<option value="" disabled="" selected="">Объем, от</option>');
						}

						if(!reset && current_to !== "" && current_to !== null)
						{
							$(".filter_engine_volume_to").append('<option value="">Любой</option>');
						}
						else
						{
							$(".filter_engine_volume_to").append('<option value="" disabled="" selected="">Объем, до</option>');
						}

						var c = 0;
						for(let i in response.engine_volumes)
						{
							var v = (response.engine_volumes[i] / 1000);
							if(v.toString().length === 1)
							{
								v = v+".0";
							}

							if(c < response.engine_volumes.length - 1)
							{
								$(".filter_engine_volume_from").append('<option value="'+response.engine_volumes[i]+'">От '+v+' л.</option>');
							}

							if(c > 0)
							{
								$(".filter_engine_volume_to").append('<option value="'+response.engine_volumes[i]+'">До '+v+' л.</option>');
							}
							c++;
						}

						if(!loaded)
						{
							if(selected['ENGINE_VOLUME_FROM'] !== undefined && selected['ENGINE_VOLUME_FROM'] !== null && selected['ENGINE_VOLUME_FROM'] !== "")
							{
								$(".filter_engine_volume_from").val(selected['ENGINE_VOLUME_FROM']);
								$(".filter_engine_volume_from").find("option").first().text("Любой").attr("disabled", false);
							}
					
							if(selected['ENGINE_VOLUME_TO'] !== undefined && selected['ENGINE_VOLUME_TO'] !== null && selected['ENGINE_VOLUME_TO'] !== "")
							{
								$(".filter_engine_volume_to").val(selected['ENGINE_VOLUME_TO']);
								$(".filter_engine_volume_to").find("option").first().text("Любой").attr("disabled", false);
							}	
						}
						else
						{
							$(".filter_engine_volume_from").val(reset ? "" : current_from);
							$(".filter_engine_volume_to").val(reset ? "" : current_to);	
						}
					}
				}

				if(used)
				{
					if(response.vehicle_types !== undefined)
					{
						if(response.vehicle_types.length > 0)
						{
							var current = $(".filter_vehicle_type").val();
							$(".filter_vehicle_type").empty();

							if(!reset && current !== "" && current !== null)
							{
								$(".filter_vehicle_type").append('<option value="">Любой</option>');
							}
							else
							{
								$(".filter_vehicle_type").append('<option value="" disabled="" selected="">Тип</option>');
							}

							for(let i in response.vehicle_types)
							{
								$(".filter_vehicle_type").append('<option value="'+response.vehicle_types[i]+'">'+response.vehicle_types[i]+'</option>');
							}

							if(!loaded)
							{
								if(selected['VEHICLE_TYPE'] !== undefined && selected['VEHICLE_TYPE'] !== null && selected['VEHICLE_TYPE'] !== "")
								{
									$(".filter_vehicle_type").val(selected['VEHICLE_TYPE']);
									$(".filter_vehicle_type").find("option").first().text("Любой").attr("disabled", false);
								}
							}
							else
							{
								$(".filter_vehicle_type").val(reset ? "" : current);
							}
						}
					}

					if(response.vehicle_subtypes !== undefined)
					{
						if(response.vehicle_subtypes.length > 0)
						{
							var current = $(".filter_vehicle_subtype").val();
							$(".filter_vehicle_subtype").empty();

							if(!reset && current !== "" && current !== null)
							{
								$(".filter_vehicle_subtype").append('<option value="">Любой</option>');
							}
							else
							{
								$(".filter_vehicle_subtype").append('<option value="" disabled="" selected="">Уточнить тип</option>');
							}

							for(let i in response.vehicle_subtypes)
							{
								$(".filter_vehicle_subtype").append('<option value="'+response.vehicle_subtypes[i]+'">'+response.vehicle_subtypes[i]+'</option>');
							}

							if(!loaded)
							{
								if(selected['VEHICLE_SUBTYPE'] !== undefined && selected['VEHICLE_SUBTYPE'] !== null && selected['VEHICLE_SUBTYPE'] !== "")
								{
									$(".filter_vehicle_subtype").val(selected['VEHICLE_SUBTYPE']);
									$(".filter_vehicle_subtype").find("option").first().text("Любой").attr("disabled", false);
								}
							}
							else
							{
								$(".filter_vehicle_subtype").val(reset ? "" : current);
							}
						}
					}

					if(response.cities !== undefined)
					{
						if(response.cities.length > 0)
						{
							var current = $(".filter_city").val();
							$(".filter_city").empty();

							if(!reset && current !== "" && current !== null)
							{
								$(".filter_city").append('<option value="">Любой</option>');
							}
							else
							{
								$(".filter_city").append('<option value="" disabled="" selected="">Город</option>');
							}

							for(let i in response.cities)
							{
								$(".filter_city").append('<option value="'+response.cities[i]+'">'+response.cities[i]+'</option>');
							}

							if(!loaded)
							{
								if(selected['PARKING_CITY'] !== undefined && selected['PARKING_CITY'] !== null && selected['PARKING_CITY'] !== "")
								{
									$(".filter_city").val(selected['PARKING_CITY']);
									$(".filter_city").find("option").first().text("Любой").attr("disabled", false);
								}
							}
							else
							{
								$(".filter_city").val(reset ? "" : current);
							}
						}
						else
						{
							$(".filter_city").empty();
							$(".filter_city").append('<option value="" disabled="" selected="">Город</option>');
							$(".filter_city").attr("disabled", "disabled");
						}
					}

					if(response.years !== undefined)
					{
						if(response.years.length > 0)
						{
							var current_from = parameters['YEAR_FROM'] !== undefined ? parameters['YEAR_FROM'] : "";
							var current_to = parameters['YEAR_TO'] !== undefined ? parameters['YEAR_TO'] : "";

							$(".filter_year_from").empty();
							$(".filter_year_to").empty();

							if(!reset && current_from !== "" && current_from !== null)
							{
								$(".filter_year_from").append('<option value="">Любой</option>');
							}
							else
							{
								$(".filter_year_from").append('<option value="" disabled="" selected="">Год, от</option>');
							}

							if(!reset && current_to !== "" && current_to !== null)
							{
								$(".filter_year_to").append('<option value="">Любой</option>');
							}
							else
							{
								$(".filter_year_to").append('<option value="" disabled="" selected="">Год, до</option>');
							}

							var c = 0;
							if(response.years.length > 1)
							{
								$(".filter_years_from").removeAttr("disabled");
								$(".filter_years_to").removeAttr("disabled");

								for(let i in response.years)
								{
									var v = response.years[i];

									if(c < response.years.length - 1)
									{
										$(".filter_year_from").append('<option value="'+response.years[i]+'">От '+v+' г.</option>');
									}

									if(c > 0)
									{
										$(".filter_year_to").append('<option value="'+response.years[i]+'">До '+v+' г.</option>');
									}
									c++;
								}
							}
							else
							{
								$(".filter_year_from").append('<option value="'+response.years[0]+'">'+response.years[0]+' г.</option>');
								$(".filter_year_to").append('<option value="'+response.years[0]+'">'+response.years[0]+' г.</option>');
								current_from = response.years[0];
								current_to = response.years[0];
								$(".filter_year_from").val(current_from);
								$(".filter_year_to").val(current_to);
								$(".filter_year_from").attr("disabled", "disabled");
								$(".filter_year_to").attr("disabled", "disabled");
							}

							if(!loaded)
							{
								if(selected['YEAR_FROM'] !== undefined && selected['YEAR_FROM'] !== null && selected['YEAR_FROM'] !== "")
								{
									$(".filter_year_from").val(selected['YEAR_FROM']);
									$(".filter_year_from").find("option").first().text("Любой").attr("disabled", false);
								}

								if(selected['YEAR_TO'] !== undefined && selected['YEAR_TO'] !== null && selected['YEAR_TO'] !== "")
								{
									$(".filter_year_to").val(selected['YEAR_TO']);
									$(".filter_year_to").find("option").first().text("Любой").attr("disabled", false);
								}
							}
							else
							{
								/*
								if(response.years.length === 1)
								{
									$(".filter_year_from").append('<option value="'+response.years[0]+'">От '+v+' г.</option>');
									$(".filter_year_to").append('<option value="'+response.years[0]+'">До '+v+' г.</option>');
									$(".filter_year_from").val(response.years[0]);
									$(".filter_year_to").val(response.years[0]);
								}
								else
								{
								*/
									$(".filter_year_from").val(reset ? "" : current_from);
									$(".filter_year_to").val(reset ? "" : current_to);
								/*
								}
								*/
							}
						}
						else
						{
							$(".filter_year_from").empty();
							$(".filter_year_from").append('<option value="" disabled="" selected="">Город</option>');
							$(".filter_year_from").attr("disabled", "disabled");
							$(".filter_year_to").empty();
							$(".filter_year_to").append('<option value="" disabled="" selected="">Город</option>');
							$(".filter_year_to").attr("disabled", "disabled");
						}
					}

					if(response.mileages !== undefined)
					{
						if(response.mileages.length > 0)
						{
							var current_from = parameters['MILEAGE_FROM'] !== undefined ? parameters['MILEAGE_FROM'] : "";
							var current_to = parameters['MILEAGE_TO'] !== undefined ? parameters['MILEAGE_TO'] : "";

							$(".filter_mileage_from").empty();
							$(".filter_mileage_to").empty();

							if(!reset && current_from !== "" && current_from !== null)
							{
								$(".filter_mileage_from").append('<option value="">Любой</option>');
							}
							else
							{
								$(".filter_mileage_from").append('<option value="" disabled="" selected="">Пробег, от</option>');
							}

							if(!reset && current_to !== "" && current_to !== null)
							{
								$(".filter_mileage_to").append('<option value="">Любой</option>');
							}
							else
							{
								$(".filter_mileage_to").append('<option value="" disabled="" selected="">Пробег, до</option>');
							}

							var c = 0;
							if(response.mileages.length > 1)
							{
								$(".filter_mileage_from").removeAttr("disabled");
								$(".filter_mileage_to").removeAttr("disabled");

								for(let i in response.mileages)
								{
									var v = (response.mileages[i] / 1000);

									if(c < response.mileages.length - 1)
									{
										$(".filter_mileage_from").append('<option value="'+response.mileages[i]+'">От '+v+' тыс. км.</option>');
									}

									if(c > 0)
									{
										$(".filter_mileage_to").append('<option value="'+response.mileages[i]+'">До '+v+' тыс. км.</option>');
									}
									c++;
								}
							}
							else
							{
								var v = (response.mileages[0] / 1000);
								$(".filter_mileage_from").append('<option selected value="'+response.mileages[0]+'">'+v+' тыс. км.</option>');
								$(".filter_mileage_to").append('<option selected value="'+response.mileages[0]+'">'+v+' тыс. км.</option>');
								current_from = response.mileages[0];
								current_to = response.mileages[0];
								$(".filter_mileage_from").val(current_from);
								$(".filter_mileage_to").val(current_to);
								$(".filter_mileage_from").attr("disabled", "disabled");
								$(".filter_mileage_to").attr("disabled", "disabled");
							}

							if(!loaded)
							{
								if(selected['MILEAGE_FROM'] !== undefined && selected['MILEAGE_FROM'] !== null && selected['MILEAGE_FROM'] !== "")
								{
									$(".filter_mileage_from").val(selected['MILEAGE_FROM']);
									$(".filter_mileage_from").find("option").first().text("Любой").attr("disabled", false);
								}

								if(selected['MILEAGE_TO'] !== undefined && selected['MILEAGE_TO'] !== null && selected['MILEAGE_TO'] !== "")
								{
									$(".filter_mileage_to").val(selected['MILEAGE_TO']);
									$(".filter_mileage_to").find("option").first().text("Любой").attr("disabled", false);
								}	
							}
							else
							{
								$(".filter_mileage_from").val(reset ? "" : current_from);
								$(".filter_mileage_to").val(reset ? "" : current_to);	
							}
						}
					}
					else
					{
						$(".filter_mileage_from").empty();
						$(".filter_mileage_from").append('<option value="" disabled="" selected="">Пробег</option>');
						$(".filter_mileage_from").attr("disabled", "disabled");
						$(".filter_mileage_to").empty();
						$(".filter_mileage_to").append('<option value="" disabled="" selected="">Пробег</option>');
						$(".filter_mileage_to").attr("disabled", "disabled");
					}
				}

				$(".catalog_filter_spinner").hide();
				$(".catalog_filter_search_button_counter").text("Показать "+response.total+" вариантов").show();
				$("#catalog_small_find").text("Показать "+response.total+" вариантов");
				total = response.total;

				if(response.total == 0)
				{
					$(".catalog_filter_search_button").attr("disabled", true);
					$("#catalog_small_find").attr("disabled", true);
				}
				else
				{
					$(".catalog_filter_search_button").attr("disabled", false);
					$("#catalog_small_find").attr("disabled", false);
				}

				updating = false;
				loaded = true;
			}, "json");
		}, 100);
	}
	else
	{
		var params = {};
		if(program !== null)
		{
			params['PROGRAM'] = program;
		}
		for(let i in parameters)
		{
			if(parameters[i] !== undefined) { params[i] = parameters[i]; }
		}
	
		counter_params = params;
	}
}

function loadModels(uid)
{
//	console.log("loadModels()", "uid", uid);
 
	$.post("/api/catalog/models/", 
	{
		USED: used, 
		BRAND_UID: uid
	}, function(response)
	{
		$(used ? "#small_filter_models_used" : "#small_filter_models").empty();
		$(used ? ".filter_models_used" : ".filter_models").empty();

		if(selected['MODEL_ID'] !== undefined)
		{
			$(used ? "#small_filter_models_used" : "#small_filter_models").append("<option value=''>Любая</option>");
			$(used ? ".filter_models_used" : ".filter_models").append("<option value=''>Любая</option>");
		}
		else
		{
			if(selected['MODEL'] !== undefined)
			{
				$(used ? "#small_filter_models_used" : "#small_filter_models").append("<option value=''>Любая</option>");
				$(used ? ".filter_models_used" : ".filter_models").append("<option value=''>Любая</option>");
			}
			else
			{
				$(used ? "#small_filter_models_used" : "#small_filter_models").append("<option value='' disabled>Модель</option>");
				$(used ? ".filter_models_used" : ".filter_models").append("<option value='' disabled>Модель</option>");
			}
		}
		if($(used ? "#small_filter_models_used" : "#small_filter_models")[0])
		{
			$(used ? "#small_filter_models_used" : "#small_filter_models")[0].selectedIndex = 0;
		}
		$(used ? ".filter_models_used" : ".filter_models")[0].selectedIndex = 0;

		for(let i in response.models)
		{
			$(used ? "#small_filter_models_used" : "#small_filter_models").append("<option value='"+response.models[i]['CODE']+"' data-id='"+response.models[i]['ID']+"' data-uid='"+response.models[i]['UID']+"'>"+response.models[i]['NAME']+"</option>");
			$(used ? ".filter_models_used" : ".filter_models").append("<option value='"+response.models[i]['CODE']+"' data-id='"+response.models[i]['ID']+"' data-uid='"+response.models[i]['UID']+"'>"+response.models[i]['NAME']+"</option>");
		}

		if(selected['MODEL'] !== undefined)
		{
			$(used ? "#small_filter_models_used" : "#small_filter_models").val(selected['MODEL']);
			$(used ? ".filter_models_used" : ".filter_models").val(selected['MODEL']);

			let id = $(used ? ".filter_models_used" : ".filter_models").find(':selected').data('id');
			let uid = $(used ? ".filter_models_used" : ".filter_models").find(':selected').data('uid');
			selected['MODEL_ID'] = id;

			loadModifications(uid);
		}
		else
		{
			updateCounter(selected);
		}
	}, "json");
}

function loadModifications(uid)
{
//	console.log("loadModifications", uid);
	$.post("/api/catalog/modifications/", 
	{
		MODEL_UID: uid
	}, function(response)
	{
		if(!used)
		{
			$(".filter_modifications").empty();

			if(selected['MODIFICATION'] !== undefined)
			{
				$(".filter_modifications").append("<option value=''>Любая</option>");
			}
			else
			{
				$(".filter_modifications").append("<option value='' disabled>Модификация</option>");
			}

			$(".filter_modifications")[0].selectedIndex = 0;

			for(let i in response.modifications)
			{
				$(".filter_modifications").append("<option value='"+response.modifications[i]['ID']+"'>"+response.modifications[i]['NAME']+"</option>");
			}

			if(selected['MODIFICATION'] !== undefined)
			{
				$(".filter_modifications").val(selected['MODIFICATION']);
			}
		}

		updateCounter(selected);
	}, "json");
}

$(function()
{
	setTimeout(init_filter, 100);
});

function handle_small_filter_brands(element, event)
{
	$(used ? ".filter_brands_used" : ".filter_brands").val(event.target.value);
	selected['MODEL'] = undefined;
	selected['MODEL_ID'] = undefined;
	selected['MODIFICATION'] = undefined;

	if($(element).val() === "")
	{
		selected['BRAND'] = undefined;
		selected['BRAND_ID'] = undefined;

		$(used ? "#small_filter_brands_used" : "#small_filter_brands").find("option").first().text("Марка").attr("disabled", "disabled");
		$(used ? "#small_filter_models_used" : "#small_filter_models").empty();
		$(used ? "#small_filter_models_used" : "#small_filter_models").append("<option value='' disabled selected>Модель</option>");
		$(used ? ".filter_brands_used" : ".filter_brands").find("option").first().text("Марка").attr("disabled", "disabled");
		$(used ? ".filter_models_used" : ".filter_models").empty();
		$(used ? ".filter_models_used" : ".filter_models").append("<option value='' disabled selected>Модель</option>");
		$(".filter_modifications").empty();
		$(".filter_modifications").append("<option disabled selected>Модификация</option>");

		updateCounter(selected);
	}
	else
	{
		let uid = $(element).find(':selected').data('uid');
		let id = $(element).find(':selected').data('id');
		selected['BRAND_ID'] = id;

		$(used ? "#small_filter_brands_used" : "#small_filter_brands").find("option").first().text("Любая").attr("disabled", false);
		$(used ? ".filter_brands_used" : ".filter_brands").find("option").first().text("Любая").attr("disabled", false);
		$(".filter_modifications").empty();
		$(".filter_modifications").append("<option disabled selected>Модификация</option>");

		loadModels(uid);
	}
}

function handle_small_filter_models(element, event)
{
	if($(element).val() === "")
	{
		$(used ? ".filter_models_used" : ".filter_models").val();

		selected['MODEL'] = undefined;
		selected['MODEL_ID'] = undefined;
		selected['MODIFICATION'] = undefined;

		$(used ? "#small_filter_models_used" : "#small_filter_models").find("option").first().text("Модель").attr("disabled", "disabled");
		$(used ? ".filter_models_used" : ".filter_models").find("option").first().text("Модель").attr("disabled", "disabled");
		$(".filter_modifications").empty();
		$(".filter_modifications").append("<option disabled selected>Модификация</option>");

		updateCounter(selected);
	}
	else
	{
		let id = $(element).find(':selected').data('id');
		let uid = $(element).find(':selected').data('uid');
		$(used ? ".filter_models_used" : ".filter_models").val(event.target.value);

		selected['MODEL'] = id;
		selected['MODEL_ID'] = id;
		selected['MODIFICATION'] = undefined;

		$(used ? "#small_filter_models_used" : "#small_filter_models").find("option").first().text("Любая").attr("disabled", false);
		$(used ? ".filter_models_used" : ".filter_models").find("option").first().text("Любая").attr("disabled", false);
		$(".filter_modifications").empty();
		$(".filter_modifications").append("<option disabled selected>Модификация</option>");

		loadModifications(uid);
	}
}

function handle_filter_brands(element)
{
	if($(element).val() === '')
	{
		selected['BRAND'] = undefined;
		selected['BRAND_ID'] = undefined;
		selected['BRAND_UID'] = undefined;
		selected['MODEL'] = undefined;
		selected['MODEL_ID'] = undefined;
		selected['MODIFICATION'] = undefined;

		$(used ? "#small_filter_brands_used" : "#small_filter_brands").find("option").first().text("Марка").attr("disabled", "disabled");
		$(used ? "#small_filter_models_used" : "#small_filter_models").empty();
		$(used ? "#small_filter_models_used" : "#small_filter_models").append("<option disabled selected>Модель</option>");
		$(used ? ".filter_brands_used" : ".filter_brands").find("option").first().text("Марка").attr("disabled", "disabled");
		$(used ? ".filter_models_used" : ".filter_models").empty();
		$(used ? ".filter_models_used" : ".filter_models").append("<option disabled selected>Модель</option>");
		$(".filter_modifications").empty();
		$(".filter_modifications").append("<option disabled selected>Модификация</option>");

		updateCounter(selected);
	}
	else
	{
		let id = $(element).find(':selected').data('id');
		let uid = $(element).find(':selected').data('uid');
		selected['BRAND'] = $(element).val();
		selected['BRAND_ID'] = id;
		selected['BRAND_UID'] = uid;
		selected['MODEL'] = undefined;
		selected['MODEL_ID'] = undefined;
		selected['MODIFICATION'] = undefined;

		$(used ? "#small_filter_brands_used" : "#small_filter_brands").find("option").first().text("Любая").attr("disabled", false);
		$(used ? ".filter_brands_used" : ".filter_brands").find("option").first().text("Любая").attr("disabled", false);
		$(".filter_modifications").empty();
		$(".filter_modifications").append("<option disabled selected>Модификация</option>");

		//console.log("selected", selected);
		//loadModels(uid);
		updateCounter(selected);
	}
}

function handle_filter_models(element)
{
	if($(element).val() === "")
	{
		selected['MODEL'] = undefined;
		selected['MODEL_ID'] = undefined;
		selected['MODIFICATION'] = undefined;

		$(used ? ".filter_models_used" : ".filter_models").find("option").first().text("Модель").attr("disabled", "disabled");

		updateCounter(selected);
	}
	else
	{
		let id = $(element).find(':selected').data('id');
		let uid = $(element).find(':selected').data('uid');
		selected['MODEL_ID'] = id;
		selected['MODIFICATION'] = undefined;

		$(used ? ".filter_models_used" : ".filter_models").find("option").first().text("Любая").attr("disabled", false);
		loadModifications(uid);
	}
}

function init_filter()
{
	$(".catalog_filter_select").attr("disabled", true);

	$("#catalog_filter_form").on("submit", function(event)
	{
		event.preventDefault();
	});

	$.get("/api/catalog/brands/", 
	{
		USED: used
	}, function(response)
	{
//		console.log("selected", selected);
		//$("#small_filter_brands").empty();
		//$("#small_filter_brands").find("option").first().text("Любая").attr("disabled", false);
		//$(".filter_brands").find("option").first().text("Любая").attr("disabled", false);

		for(let i in response.brands)
		{
			$(used ? "#small_filter_brands_used" : "#small_filter_brands").append("<option value='"+response.brands[i]['CODE']+"' data-id='"+response.brands[i]['ID']+"' data-uid='"+response.brands[i]['UID']+"'>"+response.brands[i]['NAME']+"</option>");
			$(used ? ".filter_brands_used" : ".filter_brands").append("<option value='"+response.brands[i]['CODE']+"' data-id='"+response.brands[i]['ID']+"' data-uid='"+response.brands[i]['UID']+"'>"+response.brands[i]['NAME']+"</option>");
		}

		if(selected['BRAND'] !== undefined)
		{
			$(used ? "#small_filter_brands_used" : "#small_filter_brands").find("option").first().text("Любая").attr("disabled", false).val('');
			$(used ? ".filter_brands_used" : ".filter_brands").find("option").first().text("Любая").attr("disabled", false).val('');

			$(used ? "#small_filter_brands_used" : "#small_filter_brands").val(selected['BRAND']);
			$(used ? ".filter_brands_used" : ".filter_brands").val(selected['BRAND']);

			let uid = $(used ? ".filter_brands_used" : ".filter_brands").find(':selected').data('uid');
			let id = $(used ? ".filter_brands_used" : ".filter_brands").find(':selected').data('id');
			selected['BRAND_ID'] = id;

			loadModels(uid);
		}
		else
		{
			updateCounter(selected);
		}
	}, "json");

	$("#small_filter_brands, #small_filter_brands_used").on("change", function(event)
	{
		handle_small_filter_brands(this, event);
	});

	$(".filter_brands, .filter_brands_used").on("change", function(event)
	{
		handle_filter_brands(this);
	});

	$("#small_filter_models, #small_filter_models_used").on("change", function(event)
	{
		handle_small_filter_models(this, event);
	});

	$(".filter_models, .filter_models_used").on("change", function(event)
	{
		handle_filter_models(this);
	});

	$(".filter_modifications").on("change", function(event)
	{
		if($(this).val() === "")
		{
			selected['MODIFICATION'] = undefined;

			$(".filter_modifications").find("option").first().text("Модификация").attr("disabled", "disabled");
		}
		else
		{
			selected['MODIFICATION'] = $(this).val();
			$(".filter_modifications").find("option").first().text("Любая").attr("disabled", false);
		}

		updateCounter(selected);
	});

	$("#catalog_small_form").on("submit", function(e)
	{
		e.preventDefault();
	});

	$("#catalog_small_find").on("click", function()
	{
		var p = path;

		if($(used ? "#small_filter_brands_used" : "#small_filter_brands").val() !== "" && $(used ? "#small_filter_brands_used" : "#small_filter_brands").val() !== null)
		{
			p = p + $(used ? "#small_filter_brands_used" : "#small_filter_brands").val()+"/";
		}
		if($(used ? "#small_filter_models_used" : "#small_filter_models").val() !== "" && $(used ? "#small_filter_models_used" : "#small_filter_models").val() !== null)
		{
			p = p + $(used ? "#small_filter_models_used" : "#small_filter_models").val()+"/";
		}

		window.location.href = p;
	});

	$(".catalog_filter_reset_button").on("click", function()
	{
		selected = {};
		updateCounter({}, true);
	});

	$("#rich_filter_toggle").on("click", function()
	{
		$("#catalog_special_h2").addClass("catalog_h2_title_with_filter");
		$(".container_with_filter").addClass("container_with_filter_with_margin");

		updateCounter(selected);
		$("#filter").addClass("visible").css("display", "block");
		$("#catalog_small_filter").addClass("hidden").css("display", "none");
	});

	$(".filter_bodies").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Кузов").attr("disabled", "disabled"); }

		selected['BODY'] = $(this).val();
		updateCounter(selected);
	});

	$(".filter_drives").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Привод").attr("disabled", "disabled"); }

		selected['DRIVE'] = $(this).val();;
		updateCounter(selected);
	});

	$(".filter_engine_fuels").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Двигатель").attr("disabled", "disabled"); }

		selected['ENGINE_FUEL'] = $(this).val();;
		updateCounter(selected);
	});

	$(".filter_gears").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любая").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Коробка").attr("disabled", "disabled"); }

		selected['GEAR'] = $(this).val();;
		updateCounter(selected);
	});

		//used ? ".filter_models_used" : ".filter_models"

	$(".catalog_filter_search_button").on("click", function(e)
	{
		e.preventDefault();

		if(total > 0)
		{
			var p = path;

			if($(used ? ".filter_brands_used" : ".filter_brands").val() !== undefined && $(used ? ".filter_brands_used" : ".filter_brands").val() !== null && $(used ? ".filter_brands_used" : ".filter_brands").val() !== "")
			{
				p = p + $(used ? ".filter_brands_used" : ".filter_brands").val()+"/";
			}
			if($(used ? ".filter_models_used" : ".filter_models").val() !== undefined && $(used ? ".filter_models_used" : ".filter_models").val() !== null && $(used ? ".filter_models_used" : ".filter_models").val() !== "")
			{
				p = p + $(used ? ".filter_models_used" : ".filter_models").val()+"/";
			}

			var pa = {};
			var pa_count = 0;
			var s_count = 0;

			for(let i in selected)
			{
				if(i !== "BRAND" && i !== "BRAND_ID" && i !== "BRAND_UID" && i !== "MODEL" && i !== "MODEL_ID")
				{
					if(selected[i] !== undefined && selected[i] !== null && selected[i] !== "")
					{
						pa[i] = selected[i];
						pa_count++;
					}
				}

				if(selected[i] !== undefined && selected[i] !== null && selected[i] !== '')
				{
					s_count++;
				}
			}

			if(s_count === 1)
			{
				if(selected['BODY'] !== undefined && selected['BODY'] !== null)
				{
					p = p + "kuzov-"+bodies_slugs[selected['BODY']]+"/";
					$(".catalog_filter_spinner").show();
					$(".catalog_filter_search_button_counter").html("&nbsp;");
					//$(".catalog_filter_search_button_counter").hide();
					window.location.href = p;
					return;
				}

				if(selected['ENGINE_FUEL'] !== undefined && selected['ENGINE_FUEL'] !== null)
				{
					p = p + "dvigatel-"+engine_fuels_slugs[selected['ENGINE_FUEL']]+"/";
					$(".catalog_filter_spinner").show();
					$(".catalog_filter_search_button_counter").html("&nbsp;");
					//$(".catalog_filter_search_button_counter").hide();
					window.location.href = p;
					return;
				}
			}

			if(pa_count > 0) { p = p + "?"+$.param(pa); }
			$(".catalog_filter_spinner").show();
			$(".catalog_filter_search_button_counter").html("&nbsp;");
			//$(".catalog_filter_search_button_counter").hide();
			window.location.href = p;
		}
	});

	$(".filter_engine_volume_from").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Объем, от").attr("disabled", "disabled"); }

		selected['ENGINE_VOLUME_FROM'] = $(this).val();;
		updateCounter(selected);
	});

	$(".filter_engine_volume_to").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Объем, до").attr("disabled", "disabled"); }

		selected['ENGINE_VOLUME_TO'] = $(this).val();;
		updateCounter(selected);
	});

	$(".filter_year_from").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Год, от").attr("disabled", "disabled"); }

		selected['YEAR_FROM'] = $(this).val();;
		updateCounter(selected);
	});

	$(".filter_year_to").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Год, до").attr("disabled", "disabled"); }

		selected['YEAR_TO'] = $(this).val();;
		updateCounter(selected);
	});

	$(".filter_mileage_from").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Пробег, от").attr("disabled", "disabled"); }

		selected['MILEAGE_FROM'] = $(this).val();;
		updateCounter(selected);
	});

	$(".filter_mileage_to").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Пробег, до").attr("disabled", "disabled"); }

		selected['MILEAGE_TO'] = $(this).val();;
		updateCounter(selected);
	});

	$(".filter_city").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Город").attr("disabled", "disabled"); }

		selected['PARKING_CITY'] = $(this).val();;
		updateCounter(selected);
	});

	$(".filter_vehicle_type").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Тип").attr("disabled", "disabled"); }

		selected['VEHICLE_TYPE'] = $(this).val();;
		updateCounter(selected);
	});

	$(".filter_vehicle_subtype").on("change", function()
	{
		if($(this).val() !== "")
		{ $(this).find("option").first().text("Любой").attr("disabled", false); }
		else
		{ $(this).find("option").first().text("Уточнить тип").attr("disabled", "disabled"); }

		selected['VEHICLE_SUBTYPE'] = $(this).val();;
		updateCounter(selected);
	});

	$(".sort_option").on("click", function()
	{
//		console.log("path", path);
//		console.log("current_params", current_params);

		var value = $(this).data("value");
		var p = path;
		var o = {};

		for(let i in current_params)
		{
			if(i !== "SORT" && i !== "BRAND" && i !== "MODEL" && i !== "BRAND_ID" && i !== "BRAND_UID" && i !== "MODEL_ID")
			{
				o[i] = current_params[i];
			}
		}

		if(current_params['BRAND'] !== undefined)
		{
			p = p + current_params['BRAND']+"/";
		}

		if(current_params['MODEL'] !== undefined)
		{
			p = p + current_params['MODEL']+"/";
		}

		p = p+"?";
		//if(value !== "name")
		//{
			p = p + "SORT="+value;
		//}

		var params = $.param(o);
		if(params.length > 0)
		{
			p += "&"+params;
		}

		//console.log("p", p);
		document.location.href = p;
	});

	$(".i-filter").on("click", function()
	{
		$(".filter_selector").css("display", "none");
		//$(this).parent().parent().css("display", "none");
		$("#catalog_small_filter").css("display", "block");
	});
}