PageSourceSearch

https://www.myavis.gr/themes/custom/avis2024/dist/js/filters/filters.16.1.js

js myavis.gr collected 2026-09-24 10:58:03 UTC 96,936 bytes, 2,731 lines download raw bytes

1import {getBrandTileData, getConfiguratorBrandTileData, getCarTypeTemplate, getBrandMobileFooterTemplate} from "../utils/templates.16.1.js";
2import {get} from "../api/get.16.1.js";
3import {post} from "../api/post.16.1.js";
4import {getCars} from "../api/getCars.16.1.js";
5import {makeActive, removeActive, revmoveSelected} from "../utils/utility.16.1.js";
6import {createCarFilterData, getQueryParamsFromSlash, translate, loadDictionary } from "../leasing-list/leasing-list.16.1.js";
7import {carsDataPOST, carDataCondtions as generateCarTiles} from "../configurator/configurator-details.16.1.js";
8import {getCarsByType} from "../configurator/configuratorSlider.16.1.js"
9import { metaTags } from "../metatags/metatags.16.1.js";
10
11let mobileAppliedFilters = [];
12let brandListFilter = [];
13let carTypes = [];
14let carList = [];
15let carGear = [];
16let transTypes = [];
17let fuelTypes = [];
18let typeOfFuel = [];
19let brandFilterModel = [];
20let carModelFamilyList = [];
21let modStr = "";
22window.clearFilterCalled = false;
23let brandListCarType = [];
24let  selectedBrands = [];
25
26export const handleMonthlyBudgetFilterClick = () => {};
27loadDictionary();
28
29export const getLangCode = () => {
30	let currentUrl = window.location.pathname;
31	let parts = currentUrl.split("/");
32	let languageCode = null;
33	$.each(parts, function (index, part) {
34		part = part.replace("#", "");
35		if (part.length === 2 && /^[a-z]{2}$/i.test(part)) {
36			languageCode = part;
37			return false;
38		}
39	});
40	return languageCode;
41};
42
43//query Param update by RK
44// export const updateQueryStringOnFilter = (filterKey, filterValue, isClear) => {
45// 	const currentURLDomain = decodeURIComponent(window.location.href).split("?")[0];
46// 	const queryparams = decodeURIComponent(window.location.href).split("?")[1];
47// 	const params = queryparams ? queryparams.split("/") : []; // Use "/" to split query params
48  
49// 	let pair = null;
50// 	const updatedQueryString = [];
51// 	const clearApplicableKeys = ["manufacturers", "transmission", "fuelType", "typeOfCars"];
52// 	const translateApplicableKeys = ["fuelType", "typeOfCars", "transmission"]; // Keys for which `translate` applies
53  
54// 	const urlParamsOption = getQueryParamsFromSlash(window.location.search);
55// 	const filterParam = urlParamsOption.get(filterKey);
56  
57// 	params.forEach((d) => {
58// 	  pair = d.split("=");
59// 	  const currentKey = pair[0];
60// 	  let value = pair[1];
61  
62// 	  if (isClear) {
63// 		// Clear keys in clearApplicableKeys
64// 		if (clearApplicableKeys.includes(currentKey)) {
65// 		  value = ""; // Set the value to an empty string
66// 		} else if (currentKey === "easyLeasing" || currentKey === "readyForDelivery" || currentKey === "usedCar") {
67// 		  value = 0; // Reset specific keys to 0
68// 		} else if (currentKey === "monthly_installments_min") {
69// 		  value = 80; // Reset min installments
70// 		} else if (currentKey === "monthly_installments_max") {
71// 		  value = 4500; // Reset max installments
72// 		}
73// 		if (translateApplicableKeys.includes(filterKey)) {
74// 		  value = translate(filterKey, value, "json");
75// 		}
76// 		updatedQueryString.push(`${currentKey}=${value}`);
77// 	  } else if (currentKey === filterKey) {
78// 		// Handle array of values
79// 		value = Array.isArray(filterValue)
80// 		  ? filterValue
81// 			  .map((v) =>
82// 				translateApplicableKeys.includes(filterKey)
83// 				  ? translate(filterKey, v, "json")
84// 				  : v
85// 			  )
86// 			  .join(",") // Join multiple values with commas
87// 		  : translateApplicableKeys.includes(filterKey)
88// 		  ? translate(filterKey, filterValue, "json")
89// 		  : filterValue;
90// 		// if (value != 0 && value != 1){
91// 		// 	updatedQueryString.push(`${currentKey}=${value}`);
92// 		// } else {
93// 		// 	// Find and remove the item in place using splice
94// 		// 	const index = updatedQueryString.findIndex(item => item.startsWith(`${currentKey}`));
95// 		// 	if (index !== -1) {
96// 		// 		updatedQueryString.splice(index, 1);
97// 		// 	}
98// 		// }
99// 		updatedQueryString.push(`${currentKey}=${value}`);
100// 	  } else {
101// 		// Retain other parameters as-is
102// 		updatedQueryString.push(pair.join("="));
103// 	  }
104// 	});
105  
106// 	// Add the new filterKey if it doesn't exist
107// 	if (!filterParam && !isClear) {
108// 	  const rawValue = Array.isArray(filterValue)
109// 		? filterValue
110// 			.map((v) =>
111// 			  translateApplicableKeys.includes(filterKey)
112// 				? translate(filterKey, v, "json")
113// 				: v
114// 			)
115// 			.join(",")
116// 		: translateApplicableKeys.includes(filterKey)
117// 		? translate(filterKey, filterValue, "json")
118// 		: filterValue;
119// 		if (rawValue == 1 || rawValue == 0){
120// 			updatedQueryString.push(`${filterKey}`);
121// 		} else{
122// 			updatedQueryString.push(`${filterKey}=${rawValue}`);
123// 		}
124// 	}
125  
126// 	// Join the updated query string with "/"
127// 	const urlToUpdate = [currentURLDomain, updatedQueryString.join("/")];
128// 	window.history.pushState({}, "", urlToUpdate.join("?"));
129//   };
130
131export const updateQueryStringOnFilter = (filterKey, filterValue, isClear) => {
132	// Decode the current URL and split it into domain and query parameters
133	const href = decodeURIComponent(window.location.href);
134	const [currentURLDomain, queryparams] = href.split("?");
135	const params = queryparams ? queryparams.split("/") : []; // Use "/" to split query params
136  
137	let pair = null;
138	const updatedQueryString = [];
139	const clearApplicableKeys = ["manufacturers", "transmission", "fuel-type", "type-of-cars", "search"];
140	const translateApplicableKeys = ["fuel-type", "type-of-cars", "transmission"]; // Keys for which `translate` applies
141  
142	const specialKeys = ["easyLeasing", "readyForDelivery", "usedCar"];
143  
144	const urlParamsOption = getQueryParamsFromSlash(window.location.search);
145	const filterParam = urlParamsOption.get(filterKey);
146  
147	params.forEach((d) => {
148	  pair = d.split("=");
149	  const currentKey = pair[0];
150	  let value = pair[1];
151  
152	  if (isClear) {
153		if (clearApplicableKeys.includes(currentKey) || specialKeys.includes(currentKey)) {
154		  return; // Remove the entire key from the URL
155		} else if (currentKey === "monthly_installments_min") {
156		  value = 80;
157		} else if (currentKey === "monthly_installments_max") {
158		  value = 4500;
159		}
160		if (translateApplicableKeys.includes(filterKey)) {
161		  value = translate(filterKey, value, "json");
162		}
163		updatedQueryString.push(`${currentKey}=${value}`);
164	  } else if (currentKey === filterKey) {
165		if (specialKeys.includes(filterKey)) {
166		  if (filterValue === 1 && !updatedQueryString.includes(filterKey)) {
167			updatedQueryString.push(filterKey);
168		  }
169		} else if (filterValue === null || filterValue === "" || (Array.isArray(filterValue) && filterValue.length === 0)) {
170		  return; // Remove the entire key from the URL
171		} else {
172		  value = Array.isArray(filterValue)
173			? filterValue
174				.map((v) =>
175				  translateApplicableKeys.includes(filterKey)
176					? translate(filterKey, v, "json")
177					: v
178				)
179				.join(",")
180				: (filterKey === 'search' ? filterValue 
181				: (translateApplicableKeys.includes(filterKey) 
182				? translate(filterKey, filterValue, "json") : filterValue));
183  
184		  updatedQueryString.push(`${currentKey}=${value}`);
185		}
186	  } else {
187		updatedQueryString.push(pair.join("="));
188	  }
189	});
190  
191	if (!filterParam && !isClear) {
192	  if (specialKeys.includes(filterKey)) {
193		if (filterValue === 1 && !updatedQueryString.includes(filterKey)) {
194		  updatedQueryString.push(filterKey);
195		}
196	  } else if (filterValue !== null && filterValue !== "" && (!Array.isArray(filterValue) || filterValue.length > 0)) {
197		const rawValue = Array.isArray(filterValue)
198		  ? filterValue
199			  .map((v) =>
200				translateApplicableKeys.includes(filterKey)
201				  ? translate(filterKey, v, "json")
202				  : v
203			  )
204			  .join(",")
205		  : translateApplicableKeys.includes(filterKey)
206		  ? translate(filterKey, filterValue, "json")
207		  : filterValue;
208  
209		updatedQueryString.push(`${filterKey}=${rawValue}`);
210	  }
211	}
212  
213	specialKeys.forEach((key) => {
214	  if (filterKey === key && filterValue === 0) {
215		const index = updatedQueryString.findIndex((item) => item === key);
216		if (index !== -1) {
217		  updatedQueryString.splice(index, 1);
218		}
219	  }
220	});
221  
222	const urlToUpdate = [currentURLDomain, updatedQueryString.join("/")];
223	window.history.pushState({}, "", urlToUpdate.join("?"));
224  };
225
226  
227  
228  
229  
230  
231  
232  
233
234
235
236
237
238//query Param update prmotion by RK
239
240export const updateQueryStringOnPromotion = (promotionType, promoId, isNid) => {
241	const currentURLDomain = decodeURIComponent(window.location.href).split("?")[0];
242	const queryparams = decodeURIComponent(window.location.href).split("?")[1];
243	const params = queryparams?.split("/");
244	const updatedQueryString = [];
245
246	const urlParamsOption = getQueryParamsFromSlash(window.location.search);
247
248	const typeParam = urlParamsOption.get("type");
249	if (!typeParam && promotionType !== "top_deals") {
250		updatedQueryString.push(`type=${promotionType}`);
251	}
252	params.forEach((d) => {
253		const pair = d.split("=");
254		const currentKey = pair[0];
255		if (currentKey === "type") {
256			if (promotionType !== "top_deals") {
257				updatedQueryString.push(`${currentKey}=${promotionType}`);
258			}
259		} else if (currentKey === "tid" || currentKey === "nid") {
260			const key = isNid ? "nid" : "tid";
261			let value = "";
262			if (promotionType === "top_deals") {
263				value = "all";
264			} else {
265				value = promoId;
266			}
267			updatedQueryString.push(`${key}=${value}`);
268
269			if (promotionType === "easy-leasing") {
270				updatedQueryString.push("easyLeasing");
271			}
272			if (promotionType === "ready-for-delivery") {
273				updatedQueryString.push("readyForDelivery");
274			}
275		} else if (currentKey === "easyLeasing") {
276			// const value = promotionType === "easy-leasing" ? 1 : 0;
277			// updatedQueryString.push(`${currentKey}=${value}`);
278		} else if (currentKey === "readyForDelivery") {
279			// updatedQueryString.push(`${currentKey}=0`);
280		} 
281		// else if (currentKey === "usedCar") {
282		// 	const value = promotionType === "usedCar" ? 1 : 0;
283		// 	updatedQueryString.push(`${currentKey}=${value}`);
284		// }
285	});
286	const urlToUpdate = [currentURLDomain, updatedQueryString.join("/")];
287	window.history.pushState({}, "", urlToUpdate?.join("?"));
288};
289
290
291//Getting car brands on load by RK
292(function () {
293// brandListCarType = JSON.parse(sessionStorage.getItem("manufacturerBrand"));
294//brandListCarType = await get("manufactures");
295
296	try {
297		// Attempt to retrieve the brand list from sessionStorage
298		let brandListCarType = JSON.parse(sessionStorage.getItem("manufacturerBrand"));
299
300		// If not found in sessionStorage, fetch it from the server or source
301		if (!brandListCarType) {
302			(async () => {
303				brandListCarType = await get("manufactures"); // Assuming get() fetches the data
304				sessionStorage.setItem("manufacturerBrand", JSON.stringify(brandListCarType));
305				// Further processing or initialization can happen here if necessary
306			})();
307		}
308
309		// Proceed with any further processing if necessary
310
311	} catch (error) {
312		console.error("An error occurred while fetching or processing brand data:", error);
313	}
314})();
315
316// prepare payload for Filters by RK
317const createPayloadForFilters = (isCarBrandDummyCallReqd, isclearFilter) => {
318	const fromPriceValue = parseInt($("#monthlyBudgetRangeFrom").val()); //dd1
319	const toPriceValue = parseInt($("#monthlyBudgetRangeTo").val()); // dd1
320	const $selectedMonthlyDropDown = $("#monthly-budget-dropdown");
321
322	$selectedMonthlyDropDown.text(`${fromPriceValue} - ${toPriceValue} €`).addClass("selected");
323
324	let carModels = [];
325	const manufactures = [];
326
327	const carBrands = isCarBrandDummyCallReqd ? $("#config-model-family-container input[type=checkbox]") : $("#config-model-family-container input[type=checkbox]:checked");
328
329	const carManufactures = $("#brandModalConfiguratorListing .brand-item.selected");
330
331	if (carManufactures.length > 0) {
332		carManufactures.each((index, elm) => {
333			let manufacturerName = $(elm).data("brandname");
334			let manufacturerId = $(elm).data("orderid");
335			manufactures.push({
336				id: manufacturerId,
337				name: manufacturerName,
338			});
339		});
340	} else {
341		if (!isclearFilter) {
342			const search = window.location.search.substring(1);
343			let param = JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
344			if (param["searchargs"]) {
345				let jsonparams = JSON.parse(param["searchargs"]);
346				const manufacturersFromParams = jsonparams.manufacturers || [];
347				if (manufacturersFromParams.length > 0) {
348					manufacturersFromParams.forEach(manufacturer => {
349						if (!manufactures.some(m => m.id === manufacturer.id)) {
350							manufactures.push({
351								id: manufacturer.id,
352								name: manufacturer.name,
353							});
354						}
355					});
356				}
357			}
358		}
359	}	
360
361	carBrands.each((index, element) => {
362		let modelName = element.value;
363		let modelId = element.id;
364		let manufacturerName = $(element).data("man");
365		let id = $(element).data("orderid");
366		// pushing values dor car model DD3
367		carModels.push({
368			manufacturer_name: manufacturerName,
369			modelKey: modelId,
370			name: modelName,
371		});
372
373		// DD2 data
374		if (manufactures.length === 0) {
375			manufactures.push({
376				id: id,
377				name: manufacturerName,
378			});
379		}
380	});
381
382	const $selectedModelFamilyDropDown = $("#config-model-family-filter-button");
383	let selectedModelFamilyItemLength = carModels.length;
384	let updatedModelFamilyText = "";
385	let lCode = getLangCode();
386	if (selectedModelFamilyItemLength === 0 || isCarBrandDummyCallReqd) {
387		if (lCode == "en") {
388			updatedModelFamilyText = "Model";
389		} else {
390			updatedModelFamilyText = "Μοντέλο";
391		}
392		$selectedModelFamilyDropDown.removeClass("selected");
393	} else if (selectedModelFamilyItemLength === 1) {
394		updatedModelFamilyText = carModels[0].name;
395		$selectedModelFamilyDropDown.addClass("selected");
396	} else {
397		updatedModelFamilyText = `${carModels[0].name} + ${carModels.length - 1}`;
398		$selectedModelFamilyDropDown.addClass("selected");
399	}
400	$selectedModelFamilyDropDown[0].innerText = updatedModelFamilyText;
401
402	// pushing values for car manufaturer DD4
403	// Updating the gear box dropdown text based on the selected checkbox value
404	const $checked = $("#gear-box-container-configurator input[type=checkbox]:checked");
405	const transmissions = $checked.map(function() {
406	return $(this).val(); // This returns "M" or "A"
407	}).get();
408
409	// For the dropdown display, you might want to use the data attribute:
410	const transmissionLabels = $checked.map(function() {
411	return $(this).data("entrans"); // "Manual" or "Automatic"
412	}).get();
413
414	const $dropDown = $("#config-gear-box-filter-button");
415	const langCode = getLangCode();
416	let updatedText = "";
417
418	if (transmissionLabels.length === 0) {
419		updatedText = langCode === "en" ? "Gearbox" : "Κιβώτιο";
420		$dropDown.text(updatedText).removeClass("selected");
421	} else if (transmissionLabels.length === 1) {
422		// If one option, display it (with translation if needed)
423		updatedText =
424		  langCode === "en"
425			? transmissionLabels[0]
426			: transmissionLabels[0] === "Automatic"
427			? "Αυτόματο"
428			: transmissionLabels[0] === "Manual"
429			? "Χειροκίνητο"
430			: transmissionLabels[0];
431		$dropDown.text(updatedText).addClass("selected");
432	} else {
433		// If more than one, display the first one + the count of extra options
434		let firstLabel = transmissionLabels[0];
435		if (langCode !== "en") {
436		  firstLabel = firstLabel === "Automatic" ? "Αυτόματο" : firstLabel === "Manual" ? "Χειροκίνητο" : firstLabel;
437		}
438		updatedText = `${firstLabel} + ${transmissionLabels.length - 1}`;
439		$dropDown.text(updatedText).addClass("selected");
440	}
441	
442	// pushing values dor car manufaturer DD5
443
444	const fuelType = [];
445	const typeOfFuel = [];
446	let updatedConfigFuelText = "";
447	const selectedConfigFuelDropDown = $("#config-fuel-type-filter-button");
448	const $fuelType = $("#config-fuel-type-container input[type=checkbox]:checked");
449	$fuelType.each((index, element) => {
450		let fuelValue = element.value;
451		let fuelLabel = $('label[for="' + element.id + '"]').text().trim();
452		const enVal = $(element).data("en-value");
453		fuelType.push({name: fuelValue, label: fuelLabel});
454		typeOfFuel.push({name: fuelValue, label: fuelLabel, labelEn: enVal});
455	});
456	const selectedFuelItemLength = typeOfFuel.length;
457	let languageCode = getLangCode();
458	if (selectedFuelItemLength === 0) {
459		if (languageCode == "en") {
460			updatedConfigFuelText = "Fuel Types";
461		} else {
462			updatedConfigFuelText = "Τύπος καυσίμου";
463		}
464		selectedConfigFuelDropDown.removeClass("selected");
465	} else if (selectedFuelItemLength === 1) {
466		updatedConfigFuelText = languageCode == "en" ? typeOfFuel[0]?.labelEn : typeOfFuel[0]?.label;
467		selectedConfigFuelDropDown.addClass("selected");
468	} else {
469		updatedConfigFuelText = `${languageCode == "en" ? typeOfFuel[0]?.labelEn : typeOfFuel[0]?.label} + ${typeOfFuel.length - 1}`;
470		selectedConfigFuelDropDown.addClass("selected");
471	}
472
473	selectedConfigFuelDropDown[0].innerText = updatedConfigFuelText;
474	const vehicleType = sessionStorage.getItem("selectedVehicleType") || "private";
475	const filterCarsData = {
476		fromPriceValue,
477		toPriceValue,
478		manufactures,
479		carModels,
480		transmission: transmissions,
481		fuelType,
482		vehicleType,
483	};
484	return filterCarsData;
485};
486
487// trigger post call logic by RK
488export const postFiltersData = async (isclearFilter = false, isCarBrandDummyCallReqd = false) => {
489	$("#loader-container").show();
490	const filterCarsData = createPayloadForFilters(isCarBrandDummyCallReqd, isclearFilter);
491	const fiilterdResponseData = await carsDataPOST(filterCarsData.manufactures, filterCarsData.carModels, filterCarsData.fuelType, filterCarsData.transmission.join(","), filterCarsData.fromPriceValue, filterCarsData.toPriceValue, filterCarsData.vehicleType);
492	generateCarTiles(fiilterdResponseData);
493
494	const $clearFilter = $("#config-filter-clear-all");
495	isclearFilter ? $clearFilter.addClass("invisible").removeClass("visible") : $clearFilter.addClass("visible").removeClass("invisible");
496	$("#loader-container").hide();
497};
498
499const getCarsByTypeFilter = (carTypes) => {
500	return brandListCarType.filter((el) => {
501		return carTypes.some((f) => {
502			return f?.name?.toLowerCase() === el?.brandName?.toLowerCase();
503		});
504	});
505};
506
507// display brand Modal.... change
508export const handleBrandFilterClick = async () => {
509	$("#brandModal").modal("show");
510	const modalBody = $("#brandModal .modal-body");
511	const modalContant = $("#brandModal .modal-content");
512	let cardListRow;
513	if ($(".brand-container").length) {
514		cardListRow = $(".brand-container");
515	} else {
516		cardListRow = document.createElement("div");
517		$(cardListRow).addClass("brand-container filter-brand-container row g-3 scrollbar-style-large");
518		const brandData = await getBrandList();
519		brandData.forEach((data) => {
520			const brandCard = getBrandTileData(data);
521			$(cardListRow).append(brandCard);
522		});
523		modalBody.append(cardListRow);
524	}
525	// change
526	let manufacturer_value = $("#titleId").val();
527	if (manufacturer_value && manufacturer_value === "manufacturer") {
528		const urlParams = new URLSearchParams(window.location.search);
529		let brandName = urlParams.get("brand");
530		if (brandName) {
531			const itemList = $(".brand-item");
532			let selectedItemFound = false;
533			itemList.each((index, element) => {
534				if ($(element).data("brandname") === brandName && !selectedItemFound) {
535					makeActive(element);
536					selectedItemFound = true;
537				}
538			});
539		}
540	}
541};
542
543//This is for fetching brands
544export const getBrandsModalData = async () => {
545	const modalBody = $("#brandModalConfiguratorListing .modal-body");
546	let cardListRow;
547	if ($(".brand-container").length) {
548		cardListRow = $(".brand-container");
549	} else {
550		cardListRow = document.createElement("div");
551		$(cardListRow).addClass("brand-container filter-brand-container row g-3 scrollbar-style-large");
552		const brandData = await getBrandList();
553		var search = window.location.search.substring(1);
554		if (search) {
555			jQuery(document).ready(function ($) {
556				//Use this inside your document ready jQuery
557				$(window).on("popstate", function () {
558					location.reload(true);
559				});
560			});
561			var param = JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
562			if (param["searchargs"]) {
563				var jsonparams = JSON.parse(param["searchargs"]);
564				const nameManufacture = jsonparams.models[0].manufacturer_name.toLowerCase();
565				modStr = nameManufacture[0].toUpperCase() + nameManufacture.slice(1);
566			}
567		}
568		brandData.forEach((data) => {
569			const brandCard = getBrandTileData(data);
570			$(cardListRow).append(brandCard);
571		});
572		modalBody.html(cardListRow);
573		if (!window.clearFilterCalled) {
574			$('.brand-item[data-brandName="' + modStr + '"]').addClass("selected");
575		}
576	}
577
578	$("#brandModalConfiguratorListing").modal("show");
579	const currentSelectTab = localStorage.getItem("selectedVehicleType");
580	$("#brandModalConfiguratorListing input[name='inlineCarRadioOptions']")
581		.filter('[value="' + currentSelectTab + '"]')
582		.attr("checked", true);
583};
584
585export const getConfigBrandsModalData = async () => {
586  const modalBody = $("#brandModalConfiguratorListing .modal-body");
587
588  // Show a quick loading spinner/message
589  modalBody.html('<div class="text-center py-4">Loading...</div>');
590
591  // Remove old container if any
592  // $(".brand-container").remove();
593
594  // Fetch brand data
595  const brandData = await getAvailableCars();
596  const carTypes = brandData?.[0] || [];
597  if (!brandListFilter || brandListFilter.length === 0) {
598    brandListFilter = await getBrandList();
599  }
600
601  // Filter brand list
602  const filteredBrands = brandListFilter.filter((el) =>
603    carTypes.some((f) => f?.name?.toLowerCase() === el?.brandName?.toLowerCase())
604  );
605
606  // Create container
607  const cardListRow = $("<div>")
608    .addClass("brand-container filter-brand-container row g-3 scrollbar-style-large");
609
610  // Build brand tiles
611  filteredBrands.forEach((data) => {
612    const brandCard = getConfiguratorBrandTileData(data);
613	// console.log("Fetched brandCard:", brandCard);
614    cardListRow.append(brandCard);
615  });
616
617  // Insert into modal body
618  modalBody.html(cardListRow);
619
620  // Reapply selected state
621  let selectedBrands = JSON.parse(sessionStorage.getItem("selectedCarBrand")) || [];
622  if (!Array.isArray(selectedBrands)) selectedBrands = [selectedBrands];
623  
624  $(".brand-item").removeClass("selected").each(function() {
625    const brandName = $(this).data("brandname");
626    if ( selectedBrands.some(b => 
627          typeof b === "string" 
628            ? b === brandName 
629            : b.carName === brandName
630        ) ) {
631      $(this).addClass("selected");
632    }
633  });
634  
635
636  // Show the modal
637  $("#brandModalConfiguratorListing").modal("show");
638
639  // Make sure the correct radio is checked
640  const currentSelectTab = sessionStorage.getItem("selectedVehicleType") || "private";
641  $("#brandModalConfiguratorListing input[name='inlineCarRadioOptions']")
642    .filter(`[value="${currentSelectTab}"]`)
643    .prop("checked", true);
644
645	 // **Return something** so freshData won't be undefined.
646	//  return filteredBrands; 
647};
648
649  
650  
651
652
653	let brandDataCache = {
654	private: null,
655	commercial: null
656  };	
657
658  export const getAvailableCars = async () => {
659    const selectedVehicleType = sessionStorage.getItem("selectedVehicleType") || "private";
660  
661    // Check if already cached
662    if (brandDataCache[selectedVehicleType]) {
663      return brandDataCache[selectedVehicleType];
664    }
665  
666    // Otherwise fetch from server
667    const carData = await getCars("manufacturers/" + selectedVehicleType, "");
668  
669    // Store in cache
670    brandDataCache[selectedVehicleType] = carData;
671    return carData;
672  };
673
674  // Get cars for configurator mobile
675  export const getConfigCarBrandListMobile = async () => {
676	// Determine the selected vehicle type from session storage or fallback to "private".
677	const selectedVehicleType = sessionStorage.getItem("selectedVehicleType") || "private";
678  
679	// Fetch the car brands based on the vehicle type.
680	const carData = await getCars('manufacturers/' + selectedVehicleType, "");
681	// If car data exists, process it for returning.
682	if (carData) {
683		const filteredBrands = getCarsByType(carData?.[0]);
684    let brandCard = [];
685	  filteredBrands?.forEach((data) => {
686    brandCard.push(data);
687	});
688	  return brandCard;
689	} else {
690	  console.error("No car data available for the selected vehicle type.");
691	  return [];
692	}
693  };
694
695
696//Not required now by RK
697// export const handleConfiguratorModelFamilyApplyClick = async () => {
698//   const filteredData = createPayloadForFilters();
699//   postFiltersData(filteredData);
700// };
701
702export const getModelFamilyDropDownContent = (manName, modelKey, name, id, key) => {
703	let html = "",
704		checkedOption = "";
705	if (name === key) {
706		checkedOption = "checked";
707	}
708	html += `<li class="form-check py-2">`;
709	html += `<input class="form-check-input" type="checkbox" name="modelfamily" data-man="${manName}" data-orderid = "${id}" id="${modelKey}" value="${name}" ${checkedOption}>`;
710	html += `<label class="form-check-label text-label text-secondary config-model-label">
711  ${name}
712  </label>`;
713	html += `</li>`;
714	return html;
715};
716
717$("body").click((event) => {
718	const popoverButton = $("#product-list-banner-popover");
719	if (event.target !== popoverButton) {
720		$(popoverButton).popover("hide");
721	}
722});
723
724// Price range Sorting by RK
725$(document)
726	.off("click.price")
727	.on("click.price", ".filter-wrapper-configurator #price-sorting-btn", (event) => {
728		let filteredArray = [];
729		event.stopPropagation();
730		const carsData = window.carsData?.[0];
731		if ($("#price-sorting-btn").hasClass("price-desc")) {
732			filteredArray = Object.values(carsData).sort((a, b) => a.installmentPrice - b.installmentPrice);
733		} else {
734			filteredArray = Object.values(carsData).sort((a, b) => b.installmentPrice - a.installmentPrice);
735		}
736
737		let payloadArrayData = [];
738		window.carsData = payloadArrayData.push(filteredArray);
739		$("#price-sorting-btn").toggleClass("price-desc");
740
741		generateCarTiles(payloadArrayData);
742	});
743
744	export const handleBrandFilterApplyClick = () => {
745		const selectedDropDown = $("#filter-brand-selection-button");
746		const itemList = $(".brand-item.selected");
747		const selectedItem = [];
748		const selectedItemForText = [];
749		let selectedItemLength = 0;
750		let brandListRow;
751		brandListRow = $("#model-family-container");
752	
753		// Collect data for URL query and dropdown text
754		itemList.each((index, element) => {
755			selectedItem.push($(element).data("brandname")); // For URL query
756			selectedItemForText.push($(element).find(".text-label").text().trim()); // For dropdown text
757		});
758	
759		const prevSelectedBrand = JSON.parse(localStorage.getItem("brandItems"));
760		localStorage.setItem("brandItems",JSON.stringify(selectedItem.map(item =>
760 item.replace(/-/g, " "))));
761		const newSelectedBrand = JSON.parse(localStorage.getItem("brandItems"));
762	
763		selectedItemLength = selectedItem.length;
764		// console.log("Stored Brand Items:", JSON.parse(localStorage.getItem("brandItems")));
765	
766		let text = "";
767		const languageCode = getLangCode();
768		if (selectedDropDown !== undefined) {
769			if (selectedItemLength === 0) {
770				text = languageCode === "en" ? "Car Brand" : "Κατασκευαστής";
771				selectedDropDown.removeClass("selected");
772				selectedDropDown[0].innerText = text;
773			} else if (selectedItemLength === 1) {
774				text = selectedItemForText[0]; // Use selectedItemForText for the dropdown
775				selectedDropDown.addClass("selected");
776				selectedDropDown[0].innerText = text.replace(/ and /g, " & ");
777			} else {
778				text = `${selectedItemForText[0]} + ${selectedItemForText.length - 1}`; // Use selectedItemForText for the dropdown
779				selectedDropDown.addClass("selected");
780				selectedDropDown[0].innerText = text.replace(/ and /g, " & ");
781			}
782		}
783	
784		if (selectedItemLength) {
785			if ($("#filter-clear-all").hasClass("invisible")) {
786				$("#filter-clear-all").removeClass("invisible");
787			}
788		}
789		// Use selectedItem for the URL query
790		updateQueryStringOnFilter("manufacturers", selectedItem, false);
791		createCarFilterData();
792		$("#brandModal").modal("hide");
793	};
794	
795
796// Select brand hanlder for configurator by RK
797export const handleSelectedBrands = async (e) => {
798	$("#brandModalConfiguratorListing").modal("hide");
799	const currentSelectedModelFamilyList = $("#config-model-family-container input[name=modelfamily]:checked");
800	const $selectedCarBrandDropdown = $("#configurator-filter-brand-selection-button");
801	const $selectedModelFamilyDropDown = $("#config-model-family-filter-button");
802
803	const itemList = $("#brandModalConfiguratorListing .brand-item.selected");
804	const selectedItem = [];
805	let selectBrands = [];
806	let selectedItemLength = 0;
807	const selectedModelFamilyItem = [];
808	let isTotallyNewSelectedBrands = true;
809
810	let brandListRow;
811	brandListRow = $("#model-family-container");
812	itemList.each((index, element) => {
813		selectedItem.push($(element).data("brandname"));
814		let orderId = $(element).data("orderid");
815		let orderName = $(element).data("brandname");
816		selectBrands.push({id: orderId, name: orderName});
817	});
818	let brandModelFilterData = [];
819	// Get vehicle type from sessionStorage first, then localStorage as fallback
820	const vehicleType = sessionStorage.getItem("selectedVehicleType") || localStorage.getItem("selectedVehicleType") || "private";
821	
822	// Ensure both storages have the same value
823	localStorage.setItem("selectedVehicleType", vehicleType);
824	sessionStorage.setItem("selectedVehicleType", vehicleType);
825	
826	let markersBrand = {manufacturers: selectBrands, type: vehicleType};
827	brandModelFilterData = await post("models", markersBrand);
828	let langCode = getLangCode();
829	let updatedModelFamilyTextNew = "";
830	if (langCode == "el") {
831		updatedModelFamilyTextNew = "Μοντέλο";
832	} else {
833		updatedModelFamilyTextNew = "Model";
834	}
835	$("#config-model-family-filter-button").text(updatedModelFamilyTextNew);
836	$("#config-model-family-filter-button").addClass("selected");
837
838	$(".filter-dropdown #config-model-family-container li.form-check").remove();
839
840	brandModelFilterData[0]?.forEach((response) => {
841		const modelId = selectBrands.find((o) => o.name === response?.manufacturer_name)?.id || "";
842		const getModelInputBox = getModelFamilyDropDownContent(response["manufacturer_name"], response["modelKey"], response["name"], modelId, "");
843		$("#config-model-family-container").append(getModelInputBox);
844	});
845
846	localStorage.setItem("brandItems", JSON.stringify(selectedItem));
847	currentSelectedModelFamilyList.each((index, element) => {
848		selectedModelFamilyItem.push($(element).val());
849		if (isTotallyNewSelectedBrands && selectedItem.includes($(element).data("man"))) {
850			isTotallyNewSelectedBrands = false;
851		}
852		// $(
853		//   "#config-model-family-container input[name=modelfamily][value='" +
854		//     $(element).val() +
855		//     "']"
856		// ).prop("checked", true);
857	});
858
859	// Update car brand dropdown text
860	const languageCode = getLangCode();
861	selectedItemLength = selectedItem.length;
862	let text = "";
863	if ($selectedCarBrandDropdown !== undefined) {
864		if (selectedItemLength === 0) {
865			text = languageCode === "en" ? "Car Brand" : "Κατασκευαστής";
866			$selectedCarBrandDropdown.removeClass("selected");
867			$selectedCarBrandDropdown[0].innerText = text;
868		} else if (selectedItemLength === 1) {
869			text = selectedItem[0];
870			$selectedCarBrandDropdown.addClass("selected");
871			$selectedCarBrandDropdown[0].innerText = text;
872		} else {
873			text = `${selectedItem[0]} + ${selectedItem.length - 1}`;
874			$selectedCarBrandDropdown.addClass("selected");
875			$selectedCarBrandDropdown[0].innerText = text;
876		}
877	}
878
879	// Update model family brand dropdown text
880	let updatedModelFamilyText = "";
881	if (currentSelectedModelFamilyList.length === 0) {
882		if (languageCode == "en") {
883			updatedModelFamilyText = "Model";
884		} else {
885			updatedModelFamilyText = "Μοντέλο";
886		}
887		$selectedModelFamilyDropDown.removeClass("selected");
888	} else if (currentSelectedModelFamilyList.length === 1) {
889		updatedModelFamilyText = selectedModelFamilyItem[0];
890		$selectedModelFamilyDropDown.addClass("selected");
891	} else {
892		updatedModelFamilyText = `${selectedModelFamilyItem[0]} + ${selectedModelFamilyItem.length - 1}`;
893		$selectedModelFamilyDropDown.addClass("selected");
894	}
895	$selectedModelFamilyDropDown.text(updatedModelFamilyText);
896
897	//updating clear filer status
898	if (selectedItemLength) {
899		if ($("#filter-clear-all").hasClass("invisible")) {
900			$("#filter-clear-all").removeClass("invisible");
901		} else {
902			$("#filter-clear-all").addClass("visible");
903		}
904	}
905
906	// trigger a dummy call with all selected in case of clear filter and again fetching car with new brands
907	postFiltersData(false, true);
908
909	window.clearFilterCalled = false;
910	$("#config-filter-clear-all").removeClass("invisible").addClass("visible");
911};
912
913export const handleBrandFilterSaveClick = () => {
914	//alert("brand save");
915	const selectedDropDown = $("#filter-brand-selection-button");
916	const itemList = $(".brand-item.selected");
917	const selectedItem = [];
918	let selectedItemLength = 0;
919	let brandListRow;
920	brandListRow = $("#model-family-container");
921
922	itemList.each((index, element) => {
923		selectedItem.push($(element).data("brandname"));
924	});
925
926	selectedItem.forEach(async (response) => {
927		brandFilterModel = await get("make/" + response);
928		brandFilterModel.forEach((data) => {
929			const brandModelCard = getCarTypeTemplate(data);
930			$(brandListRow).append(brandModelCard);
931		});
932	});
933
934	selectedItemLength = selectedItem.length;
935
936	let text = "";
937	const languageCode = getLangCode();
938	if (selectedItemLength === 0) {
939		text = languageCode === "en" ? "Car Brand" : "Κατασκευαστής";
940		selectedDropDown.removeClass("selected");
941	} else if (selectedItemLength === 1) {
942		text = selectedItem[0];
943		selectedDropDown.addClass("selected");
944	} else {
945		text = `${selectedItem[0]} + ${selectedItem.length - 1}`;
946		selectedDropDown.addClass("selected");
947		selectedDropDown[0].innerText = text;
948	}
949
950	if (selectedItemLength) {
951		if ($("#filter-clear-all").hasClass("invisible")) {
952			$("#filter-clear-all").removeClass("invisible");
953		}
954	}
955	$("#brandModal").modal("hide");
956};
957
958// On Search Topdeals update results
959// intercept the search form submit
960$('#topdeal-search').on('submit', 'form.search-form', function(e) {
961	e.preventDefault();
962	var query = $.trim($(this).find('input[name="search"]').val());
963	if (!query) return;
964
965	const logUrl = (drupalSettings.path.baseUrl || '/') + 'search_field/log';
966    const payload = new URLSearchParams({ term: query });
967
968      // 1) fetch a fresh CSRF token
969      fetch((drupalSettings.path.baseUrl || '/') + 'session/token', {
970        credentials: 'same-origin'
971      })
972      .then(r => r.text())
973      .then(token => {
974        // 2) fire‐and‐forget your log with keepalive
975        fetch(logUrl, {
976          method: 'POST',
977          headers: {
978            'Content-Type': 'application/x-www-form-urlencoded',
979            'X-CSRF-Token': token,
980          },
981          body: payload,
982          keepalive: true
983        }).catch(console.error);
984      })
985      .catch(console.error);
986	
987	$(this).find('.top-deals-search-blur').trigger('click');
988	$(this).find('#topdeals-results').empty().hide();
989	$(this).find('input[name="search"]').blur();
990  
991	// update URL/query state just like other filters
992	updateQueryStringOnFilter('search', [ query ], false);
993  
994	// show “clear all” if needed
995	$('#filter-clear-all').removeClass('invisible');
996  
997	// re-run the same pipeline that applies filters
998	createCarFilterData();
999  });
1000
1001// Apply Topdeals filter onClick, or on Button click
1002function handleFilterApply(filterType) {
1003	let selectedItem = [];
1004	let selectedItemLength = 0;
1005	let updatedText = "";
1006	let selectedDropDown;
1007	let filterKey = "";
1008
1009	if (filterType === "type-of-cars") {
1010		selectedDropDown = $("#type-of-car-filter-button");
1011		const itemList = $("#type-of-car-container input[type=checkbox]:checked");
1012		itemList.each((index, element) => selectedItem.push(element.value));
1013
1014		selectedItemLength = selectedItem.length;
1015		let languageCode = getLangCode();
1016		if (selectedItemLength === 0) {
1017			updatedText = languageCode === "en" ? "Type of Car" : "Τύπος αυτοκινήτου";
1018			selectedDropDown.removeClass("selected");
1019		} else if (selectedItemLength === 1) {
1020			updatedText = selectedItem[0];
1021			selectedDropDown.addClass("selected");
1022		} else {
1023			updatedText = `${selectedItem[0]} + ${selectedItemLength - 1}`;
1024			selectedDropDown.addClass("selected");
1025		}
1026
1027		filterKey = "type-of-cars";
1028	} else if (filterType === "monthly-budget") {
1029		const fromVal = $("#monthlyBudgetRangeFrom").val();
1030		const toVal = $("#monthlyBudgetRangeTo").val();
1031		updatedText = `${fromVal} - ${toVal} €`;
1032		selectedDropDown = $("#monthly-budget-dropdown");
1033		selectedDropDown.addClass("selected");
1034		filterKey = "monthly-budget";
1035		selectedItem = [fromVal, toVal];
1036	} else if (filterType === "gearBox") {
1037		selectedDropDown = $("#gear-box-filter-button");
1038		const itemList = $("#gear-box-container input[type=checkbox]:checked");
1039		itemList.each((index, element) => selectedItem.push(element.value));
1040		selectedItemLength = selectedItem.length;
1041		let languageCode = getLangCode();
1042		updatedText = selectedItemLength === 0
1043			? (languageCode === "en" ? "Gearbox" : "Κιβώτιο")
1044			: selectedItemLength === 1
1045			? selectedItem[0]
1046			: `${selectedItem[0]} + ${selectedItemLength - 1}`;
1047		selectedDropDown.toggleClass("selected", selectedItemLength > 0);
1048		filterKey = "transmission";
1049	} else if (filterType === "fuel-type") {
1050		selectedDropDown = $("#fuel-type-filter-button");
1051		const itemList = $("#fuel-type-container input[type=checkbox]:checked");
1052		itemList.each((index, element) => selectedItem.push(element.value));
1053		selectedItemLength = selectedItem.length;
1054		let languageCode = getLangCode();
1055		updatedText = selectedItemLength === 0
1056			? (languageCode === "en" ? "Fuel Types" : "Τύπος καυσίμου")
1057			: selectedItemLength === 1
1058			? selectedItem[0]
1059			: `${selectedItem[0]} + ${selectedItemLength - 1}`;
1060		selectedDropDown.toggleClass("selected", selectedItemLength > 0);
1061		filterKey = "fuel-type";
1062	} else if (filterType === "modelFamily") {
1063		selectedDropDown = $("#model-family-filter-button");
1064		const itemList = $("#model-family-container input[type=checkbox]:checked");
1065		itemList.each((index, element) => selectedItem.push(element.value));
1066		selectedItemLength = selectedItem.length;
1067		let languageCode = getLangCode();
1068		updatedText = selectedItemLength === 0
1069			? (languageCode === "en" ? "Model" : "Μοντέλο")
1070			: selectedItemLength === 1
1071			? selectedItem[0]
1072			: `${selectedItem[0]} + ${selectedItemLength - 1}`;
1073		selectedDropDown.toggleClass("selected", selectedItemLength > 0);
1074		filterKey = "modelFamily";
1075	}
1076
1077	if (selectedDropDown && selectedDropDown.length > 0) {
1078		selectedDropDown[0].innerText = updatedText;
1079		// Hide to have the dropdown menus open even when on click.
1080		// selectedDropDown.dropdown("toggle");
1081	}
1082
1083	updateQueryStringOnFilter(filterKey, selectedItem, false);
1084
1085	if (selectedItemLength || selectedItem.length) {
1086		$("#filter-clear-all").removeClass("invisible");
1087	}
1088
1089	const lang = getLangCode();
1090	metaTags(lang);
1091
1092	if (filterType === "monthly-budget") {
1093		let fromValue = parseFloat($("#monthlyBudgetRangeFrom").val());
1094		let toValue = parseFloat($("#monthlyBudgetRangeTo").val());
1095		if (fromValue > toValue) {
1096			alert("The 'From' value cannot be greater than the 'To' value.");
1097			return;
1098		}
1099	}
1100
1101	createCarFilterData();
1102}
1103
1104$(document).on("change", ".form-check-input", function () {
1105	const filterType = $(this).closest("ul").data("filter-type");
1106	if (filterType) handleFilterApply(filterType);
1107});
1108
1109$(document).on("click", ".apply-filter-button", function (event) {
1110	const filterType = event.currentTarget.dataset["filterType"];
1111	if (filterType) handleFilterApply(filterType);
1112});
1113
1114
1115
1116//clear filter by RK
1117$(document)
1118	.off("click.clearFilter")
1119	.on("click.clearFilter", ".filter-wrapper-configurator #config-filter-clear-all", (event) => {
1120		event.preventDefault();
1121		window.clearFilterCalled = true;
1122		filterTextResetConfigurator();
1123		// Make the model family filter empty on clear all click
1124		$("#config-model-family-container li.form-check").remove();
1125
1126
1127			// Custom clear logic for nested searchargs:
1128			const currentUrl = new URL(window.location.href);
1129			if (currentUrl.searchParams.has("searchargs")) {
1130			try {
1131				const searchArgs = JSON.parse(currentUrl.searchParams.get("searchargs"));
1132				// Clear the filters by setting manufacturers and models to empty arrays
1133				searchArgs.manufacturers = [];
1134				searchArgs.models = [];
1135				// Update the searchargs parameter with the cleared filters
1136				currentUrl.searchParams.set("searchargs", JSON.stringify(searchArgs));
1137				// Update the browser URL without reloading the page
1138				window.history.pushState({}, "", decodeURIComponent((currentUrl.toString())));
1139			} catch (e) {
1140				console.error("Error parsing searchargs:", e);
1141			}
1142			}
1143
1144		//Request new data
1145		postFiltersData(true);
1146		$(event.currentTarget).toggleClass("invisible");
1147	});
1148
1149export const filterTextResetConfigurator = () => {
1150	const monthlyBudgetDropdownElement = $(".filter-wrapper-configurator #config-monthly-budget-dropdown");
1151	const brandSelectionDropdownElement = $(".filter-wrapper-configurator #configurator-filter-brand-selection-button");
1152	const modelFalimyDropdownElement = $(".filter-wrapper-configurator #config-model-family-filter-button");
1153	const gearBoxDropDownElment = $(".filter-wrapper-configurator #config-gear-box-filter-button");
1154	const fuelTypeDropDownElement = $(".filter-wrapper-configurator #config-fuel-type-filter-button");
1155
1156	// Clear Car brand Data
1157	$("#brandModalConfiguratorListing .brand-item").removeClass("selected");
1158
1159	//clear car object
1160	window.carsData = [];
1161
1162	// Clear selected values
1163	$("#brandModalConfiguratorListing .brand-item").removeClass("selected");
1164	$("#config-model-family-container input[name=modelfamily]").prop("checked", false);
1165	$("#gear-box-container-configurator input[name=gearBoxInput]").prop("checked", false);
1166	$("#config-fuel-type-container input[name=fuel]").prop("checked", false);
1167	$("#monthlyBudgetRangeFrom").val(80);
1168	$("#monthlyBudgetRangeTo").val(4500);
1169	
1170	// Prioritize sessionStorage value over UI selection
1171	const vehicleTypeFromSession = sessionStorage.getItem("selectedVehicleType");
1172	const currentSelection = vehicleTypeFromSession || $('input[name="inlineCarRadioOptions"]:checked').val() || "private";
1173	
1174	// Ensure both localStorage and sessionStorage have the same value
1175	localStorage.setItem("selectedVehicleType", currentSelection);
1176	sessionStorage.setItem("selectedVehicleType", currentSelection);
1177	
1178	// Update UI to match the current selection from sessionStorage
1179	$('input[name="inlineCarRadioOptions"]').prop("checked", false); // Uncheck all first
1180	$('input[name="inlineCarRadioOptions"][value="' + currentSelection + '"]').prop("checked", true);
1181
1182	// Remove selected class
1183	$(".filter-wrapper-configurator .dropdown-toggle").removeClass("selected");
1184
1185	// reset clear all
1186	$(".filter-wrapper-configurator #config-filter-clear-all").removeClass("visible").addClass("invisible");
1187
1188	// change text to default selected class
1189	let languageCode = getLangCode();
1190
1191	if (languageCode == "en") {
1192		monthlyBudgetDropdownElement.text("Monthly budget");
1193		brandSelectionDropdownElement.text("Manufacturer");
1194		modelFalimyDropdownElement.text("Model");
1195		gearBoxDropDownElment.text("Gearbox");
1196		fuelTypeDropDownElement.text("Fuel type");
1197	} else {
1198		monthlyBudgetDropdownElement.text("Μηνιαίο μίσθωμα");
1199		brandSelectionDropdownElement.text("Κατασκευαστής");
1200		modelFalimyDropdownElement.text("Μοντέλο");
1201		gearBoxDropDownElment.text("Κιβώτιο");
1202		fuelTypeDropDownElement.text("Τύπος καυσίμου");
1203	}
1204	
1205	// Reload data with the current vehicle type
1206	postFiltersData(true);
1207};
1208
1209export const filterTextReset = () => {
1210	const carTypeDropDownElment = $("#type-of-car-filter-button");
1211	carTypeDropDownElment.removeClass("selected");
1212	const gearBoxDropDownElment = $("#gear-box-filter-button");
1213	gearBoxDropDownElment.removeClass("selected");
1214	const fuelTypeDropDownElement = $("#fuel-type-filter-button");
1215	fuelTypeDropDownElement.removeClass("selected");
1216	const monthlyBudgetDropdownElement = $("#monthly-budget-dropdown");
1217	monthlyBudgetDropdownElement.removeClass("selected");
1218	const brandSelectionDropdownElement = $("#filter-brand-selection-button");
1219	brandSelectionDropdownElement.removeClass("selected");
1220
1221	let languageCode = getLangCode();
1222	if (languageCode == "en") {
1223		carTypeDropDownElment[0].innerText = "Car type";
1224		gearBoxDropDownElment[0].innerText = "Gearbox";
1225		fuelTypeDropDownElement[0].innerText = "Fuel type";
1226		monthlyBudgetDropdownElement[0].innerText = "Monthly budget";
1227		brandSelectionDropdownElement[0].innerText = "Manufacturer";
1228	} else {
1229		carTypeDropDownElment[0].innerText = "Τύπος αυτοκινήτου";
1230		gearBoxDropDownElment[0].innerText = "Κιβώτιο";
1231		fuelTypeDropDownElement[0].innerText = "Τύπος καυσίμου";
1232		monthlyBudgetDropdownElement[0].innerText = "Μηνιαίο μίσθωμα";
1233		brandSelectionDropdownElement[0].innerText = "Κατασκευαστής";
1234	}
1235};
1236
1237export const resetSelectedFilters = () => {
1238	resetBrandFilter();
1239	resetCarTypes();
1240	resetMonthlyBudget();
1241	resetGearBox();
1242	resetFuelType();
1243};
1244
1245const resetCarTypes = () => {
1246	const carTypeList = $("#type-of-car-container input[type=checkbox]:checked");
1247	carTypeList.each((index, element) => {
1248		$(element).prop("checked", false);
1249	});
1250};
1251
1252const resetMonthlyBudget = () => {
1253	$("#monthlyBudgetRangeFrom").val("80");
1254	$("#monthlyBudgetRangeTo").val("4500");
1255};
1256
1257const resetBrandFilter = () => {
1258	$(".brand-item").removeClass("selected");
1259};
1260
1261const resetGearBox = () => {
1262	const carTypeList = $("#gear-box-container input[type=checkbox]:checked");
1263	carTypeList.each((index, element) => {
1264		$(element).prop("checked", false);
1265	});
1266};
1267
1268const resetFuelType = () => {
1269	const carTypeList = $("#fuel-type-container input[type=checkbox]:checked");
1270	carTypeList.each((index, element) => {
1271		$(element).prop("checked", false);
1272	});
1273};
1274
1275const pageImage = async (nid) => {
1276	let image = await get("getPageImage/" + nid);
1277	return image;
1278};
1279const getPromotion = async () => {
1280	const data = await get("promotion");
1281	return data;
1282};
1283const getPromotionCount = async (tid) => {
1284	let promoCount = await get("promotionCount/" + tid);
1285	return promoCount;
1286};
1287const getTopDealsCount = async () => {
1288	let topCount = await get("topDealsCount");
1289	return topCount;
1290};
1291const getGreenCount = async () => {
1292	let greenCount = await get("greenDealsCount");
1293	return greenCount;
1294};
1295const getEasyLeasingCount = async () => {
1296	let easyCount = await get("easyLeasingCount");
1297	return easyCount;
1298};
1299const getPromotionById = async (id) => {
1300	let getPromo = await get("getPromotionById/" + id);
1301	return getPromo;
1302};
1303
1304if (document.querySelector("#listing-banner-container")) {
1305	const urlParams = getQueryParamsFromSlash(window.location.search);
1306	if (urlParams.has("type")) {
1307		let type = urlParams.get("type");
1308		if (type == "promotion") {
1309			let tid = urlParams.get("tid");
1310			let promoCount = await getPromotionCount(tid);
1311			$(".dCount").html(promoCount[0].Id + " ");
1312		} else if (type == "green-deals") {
1313			let greenCount = await getGreenCount();
1314			$(".dCount").html(greenCount[0].Id + " ");
1315		} else if (type == "easy-leasing") {
1316			let easyCount = await getEasyLeasingCount();
1317			$(".dCount").html(easyCount[0].Id + " ");
1318		}
1319	} else {
1320		let topCount = await getTopDealsCount();
1321		$(".dCount").html(topCount[0].Id + " ");
1322	}
1323	if (urlParams.has("easyLeasing")) {
1324		let easy = urlParams.get("easyLeasing");
1325		if (easy == 1) {
1326			$("#flexSwitchCheckDefaultEasy").prop("checked", true);
1327		} else {
1328			$("#flexSwitchCheckDefaultEasy").prop("checked", false);
1329		}
1330	}
1331	if (urlParams.has("readyForDelivery")) {
1332		let ready = urlParams.get("readyForDelivery");
1333		if (ready == 1) {
1334			$("#flexSwitchCheckCheckedReady").prop("checked", true);
1335		} else {
1336			$("#flexSwitchCheckCheckedReady").prop("checked", false);
1337		}
1338	}
1339	if (urlParams.has("usedCar")) {
1340		let used = urlParams.get("usedCar");
1341		if (used == 1) {
1342			$("#flexSwitchCheckUsedCar").prop("checked", true);
1343		} else {
1344			$("#flexSwitchCheckUsedCar").prop("checked", false);
1345		}
1346	}
1347}
1348
1349//mobile view filter change
1350$(document).on("click", ".deals_dropdown", async (event) => {
1351	let topCount = await getTopDealsCount();
1352	$(".top-count").html(topCount[0].Id + " ");
1353	let greenCount = await getGreenCount();
1354	$(".green-count").html(greenCount[0].Id + " ");
1355	let easyCount = await getEasyLeasingCount();
1356	$(".easy-count").html(easyCount[0].Id + " ");
1357
1358	let allPromotion = await getPromotion();
1359	allPromotion.forEach(async (item) => {
1360		let promoCount = await getPromotionCount(item.tid);
1361		$(".pcount-" + item.tid).html(promoCount[0].Id + " ");
1362	});
1363
1364	//let selectedItem = $(".dTitle").data("id");
1365	if (localStorage.getItem("selectedBannerItem")) {
1366		let selectedItem = localStorage.getItem("selectedBannerItem");
1367		//localStorage.setItem("selectedMobileBannerItem", selectedItem);
1368		$("img.check-desk-img").addClass("invisible");
1369		$(".desk-banner-item").addClass("subtitle-bold").removeClass("h5 selected");
1370		$(".select-" + selectedItem)
1371			.addClass("h5 selected")
1372			.removeClass("subtitle-bold");
1373
1374		$(".img-" + selectedItem).removeClass("invisible");
1375	}
1376	if (localStorage.getItem("selectedMobileBannerItem")) {
1377		let selectedMobileItem = localStorage.getItem("selectedMobileBannerItem");
1378		//localStorage.setItem("selectedBannerItem", selectedMobileItem);
1379		$("img.check-img").addClass("invisible");
1380		$(".banner-item").addClass("subtitle-bold").removeClass("h5 selected");
1381		$(".selectItem-" + selectedMobileItem)
1382			.addClass("h5 selected")
1383			.removeClass("subtitle-bold");
1384
1385		$(".imgItem-" + selectedMobileItem).removeClass("invisible");
1386	}
1387});
1388
1389export const handleDesktopBannerSelection = async (event) => {
1390	let dId = "";
1391	let nid = $(event.currentTarget).data("id");
1392
1393	const type = $(event.currentTarget).data("type");
1394	const isNidParam = $(event.currentTarget).data("identifier") === "tid" ? false : true;
1395
1396	$("#flexSwitchCheckDefaultEasy").removeClass("disableEasyLeasing");
1397	$("#flexSwitchCheckCheckedReady").removeClass("disableEasyLeasing");
1398	$("#flexSwitchCheckUsedCar").removeClass("disableEasyLeasing");
1399	$(".product-list-banner-popover img.check-desk-img").addClass("invisible");
1400	$(".desk-banner-item").addClass("subtitle-bold").removeClass("h5 selected");
1401	event.currentTarget.querySelector("img.check-desk-img").classList.remove("invisible");
1402	$(event.currentTarget).addClass("h5 selected").removeClass("subtitle-bold");
1403
1404	let count = $(event.currentTarget).find(".count").text();
1405	let selectedItem;
1406	let selectedTitle = "";
1407	let bannerChangeId = event.currentTarget.id;
1408	if (event.currentTarget.id === "banner-top-deal" || event.currentTarget.id === "banner-green-deal" || event.currentTarget.id === "banner-easy-leasing") {
1409		const data = await pageImage(nid);
1410		selectedItem = data[0].mainImage;
1411		selectedTitle = data[0].title;
1412
1413		if (bannerChangeId === "banner-top-deal") {
1414			dId = "top_deals";
1415		} else if (bannerChangeId === "banner-green-deal") {
1416			dId = "green-deals";
1417		} else if (bannerChangeId === "banner-easy-leasing") {
1418			dId = "easy-leasing";
1419		}
1420	} else if (bannerChangeId === "banner-" + nid) {
1421		const data = await getPromotionById(nid);
1422		selectedItem = data[0].mainImage;
1423		selectedTitle = data[0].name;
1424		dId = nid;
1425	}
1426	if (selectedItem) {
1427		$(".bg-image").css("background-image", "url(" + selectedItem + ")");
1428		$(".dTitle").html(selectedTitle);
1429		$(".dCount").html(count);
1430		$(".dTitle").attr("data-titleid", dId);
1431		$("#titleId").val(dId);
1432		localStorage.setItem("selectedBannerItem", dId);
1433	}
1434	const brandSelectionDropdownElement = $("#filter-brand-selection-button");
1435
1436	if (brandSelectionDropdownElement) {
1437		brandSelectionDropdownElement.attr("disabled", false);
1438	}
1439
1440	filterTextReset();
1441	resetSelectedFilters();
1442	if (bannerChangeId === "banner-easy-leasing") {
1443		$("#flexSwitchCheckDefaultEasy").prop("checked", true);
1444		$("#flexSwitchCheckDefaultEasy").addClass("disableEasyLeasing");
1445	} else {
1446		$("#flexSwitchCheckDefaultEasy").prop("checked", false);
1447	}
1448	if (bannerChangeId === "banner-365") {
1449		$("#flexSwitchCheckCheckedReady").prop("checked", true);
1450		$("#flexSwitchCheckCheckedReady").addClass("disableEasyLeasing");
1451	} else {
1452		$("#flexSwitchCheckCheckedReady").prop("checked", false);
1453	}
1454	if (bannerChangeId === "banner-416") {
1455		$("#flexSwitchCheckUsedCar").prop("checked", true);
1456		$("#flexSwitchCheckUsedCar").addClass("disableEasyLeasing");
1457	} else {
1458		$("#flexSwitchCheckUsedCar").prop("checked", false);
1459	}
1460	localStorage.removeItem("brandItems");
1461
1462	updateQueryStringOnPromotion(type, nid, isNidParam);
1463	createCarFilterData(dId);
1464	$('#topdeals-clear').trigger('click');
1465};
1466
1467// export const handleDesktopBannerSelection = async (event) => {
1468// 	event.preventDefault();
1469// 	event.stopPropagation();
1470  
1471// 	// Clear previous desktop banner selections
1472// 	$(".desk-banner-item")
1473// 	  .removeClass("h5 selected")
1474// 	  .addClass("subtitle-bold")
1475// 	  .find("img.check-desk-img")
1476// 	  .addClass("invisible");
1477  
1478// 	const $target = $(event.currentTarget);
1479// 	const bannerId = event.currentTarget.id; // e.g. "banner-easy-leasing"
1480// 	const nid = $target.data("id");           // e.g. 877
1481// 	const type = $target.data("type");          // e.g. "easy-leasing"
1482// 	const isNidParam = $target.data("identifier") === "tid" ? false : true;
1483  
1484// 	// Immediately mark the clicked banner as selected
1485// 	$target.removeClass("subtitle-bold").addClass("h5 selected");
1486// 	$target.find("img.check-desk-img").removeClass("invisible");
1487  
1488// 	// Get count, image, and title data
1489// 	let count = $target.find(".count").text();
1490// 	let selectedItem, selectedTitle = "";
1491// 	let dId = "";
1492  
1493// 	if (bannerId === "banner-easy-leasing") {
1494// 	  const data = await pageImage(nid);
1495// 	  selectedItem = data[0].mainImage;
1496// 	  selectedTitle = data[0].title;
1497// 	  dId = "easy-leasing";
1498// 	} else if (bannerId === "banner-top-deal") {
1499// 	  const data = await pageImage(nid);
1500// 	  selectedItem = data[0].mainImage;
1501// 	  selectedTitle = data[0].title;
1502// 	  dId = "top_deals";
1503// 	} else if (bannerId === "banner-green-deal") {
1504// 	  const data = await pageImage(nid);
1505// 	  selectedItem = data[0].mainImage;
1506// 	  selectedTitle = data[0].title;
1507// 	  dId = "green-deals";
1508// 	} else if (bannerId === "banner-" + nid) {
1509// 	  const data = await getPromotionById(nid);
1510// 	  selectedItem = data[0].mainImage;
1511// 	  selectedTitle = data[0].name;
1512// 	  dId = nid;
1513// 	}
1514  
1515// 	if (selectedItem) {
1516// 	  $(".bg-image").css("background-image", "url(" + selectedItem + ")");
1517// 	  $(".dTitle").html(selectedTitle);
1518// 	  $(".dCount").html(count);
1519// 	  $(".dTitle").attr("data-titleid", dId);
1520// 	  $("#titleId").val(dId);
1521// 	  // Save the selection in localStorage
1522// 	  localStorage.setItem("selectedBannerItem", dId);
1523// 	}
1524  
1525// 	// Update the URL and reapply filter criteria
1526// 	updateQueryStringOnPromotion(type, nid, isNidParam);
1527// 	createCarFilterData(dId);
1528  
1529// 	// After a short delay, re-render the banner selection based on localStorage
1530// 	setTimeout(() => {
1531// 	  const selectedBanner = localStorage.getItem("selectedBannerItem");
1532// 	  $(".desk-banner-item").each(function () {
1533// 		const $item = $(this);
1534// 		// We compare the element's data-type with the stored value.
1535// 		if ($item.data("type") === selectedBanner) {
1536// 		  $item.addClass("h5 selected").removeClass("subtitle-bold");
1537// 		  $item.find("img.check-desk-img").removeClass("invisible");
1538// 		} else {
1539// 		  $item.removeClass("h5 selected").addClass("subtitle-bold");
1540// 		  $item.find("img.check-desk-img").addClass("invisible");
1541// 		}
1542// 	  });
1543// 	}, 1500);
1544//   };
1545  
1546  
1547
1548export const handleProductListBannerSelection = async (event) => {
1549	// Close the offcanvas
1550	const offcanvasElement = document.getElementById("offcanvasResponsive");
1551	const bsOffcanvas = bootstrap.Offcanvas.getInstance(offcanvasElement);
1552	if (bsOffcanvas) {
1553		bsOffcanvas.hide();
1554	}
1555
1556	let dId = "";
1557	let nid = $(event.currentTarget).data("id");
1558
1559	const type = $(event.currentTarget).data("type");
1560	const isNidParam = $(event.currentTarget).data("identifier") === "tid" ? false : true;
1561	// to hide the check image
1562	$("#flexSwitchCheckDefaultEasy").removeClass("disableEasyLeasing");
1563	$("#flexSwitchCheckCheckedReady").removeClass("disableEasyLeasing");
1564	$("#flexSwitchCheckUsedCar").removeClass("disableEasyLeasing");
1565	$("img.check-img").addClass("invisible");
1566	$(".banner-item").addClass("subtitle-bold").removeClass("h5 selected");
1567
1568	// add checked image only for the selected banner
1569	event.currentTarget.querySelector("img.check-img").classList.remove("invisible");
1570	// $(".select-" + nid)
1571	//   .find("img.check-img")
1572	//   .remove("invisible");
1573
1574	// $(event.currentTarget).addClass("h5 selected").removeClass("subtitle-bold");
1575	$(".selectItem-" + nid)
1576		.addClass("h5 selected")
1577		.removeClass("subtitle-bold");
1578
1579	let count = $(event.currentTarget).find(".count").text();
1580	let selectedItem;
1581	let selectedTitle = "";
1582	let mobileBannerChangeId = event.currentTarget.id;
1583	if (event.currentTarget.id === "banner-top-deal" || event.currentTarget.id === "banner-green-deal" || event.currentTarget.id === "banner-easy-leasing") {
1584		const data = await pageImage(nid);
1585		selectedItem = data[0].mainImage;
1586		selectedTitle = data[0].title;
1587		if (mobileBannerChangeId === "banner-top-deal") {
1588			dId = "top_deals";
1589		} else if (mobileBannerChangeId === "banner-green-deal") {
1590			dId = "green-deals";
1591		} else if (mobileBannerChangeId === "banner-easy-leasing") {
1592			dId = "easy-leasing";
1593		}
1594	} else if (mobileBannerChangeId === "banner-" + nid) {
1595		const data = await getPromotionById(nid);
1596		selectedItem = data[0].mainImage;
1597		selectedTitle = data[0].name;
1598		dId = nid;
1599	}
1600	if (selectedItem) {
1601		$(".bg-image").css("background-image", "url(" + selectedItem + ")");
1602		$(".dTitleMobile").html(selectedTitle);
1603		$(".dCount").html(count);
1604		$(".dTitleMobile").attr("data-id", dId);
1605		$("#mobileTitle").val(dId);
1606		localStorage.setItem("selectedMobileBannerItem", dId);
1607	}
1608	updateQueryStringOnPromotion(type, nid, isNidParam);
1609	clearMobileFilter();
1610
1611	if (mobileBannerChangeId === "banner-easy-leasing") {
1612		$("#flexSwitchCheckDefaultEasy").prop("checked", true);
1613		$("#flexSwitchCheckDefaultEasy").addClass("disableEasyLeasing");
1614	} else {
1615		$("#flexSwitchCheckDefaultEasy").prop("checked", false);
1616	}
1617	if (mobileBannerChangeId === "banner-365") {
1618		$("#flexSwitchCheckCheckedReady").prop("checked", true);
1619		$("#flexSwitchCheckCheckedReady").addClass("disableEasyLeasing");
1620	} else {
1621		$("#flexSwitchCheckCheckedReady").prop("checked", false);
1622	}
1623	if (mobileBannerChangeId === "banner-416") {
1624		$("#flexSwitchCheckUsedCar").prop("checked", true);
1625		$("#flexSwitchCheckUsedCar").addClass("disableEasyLeasing");
1626	} else {
1627		$("#flexSwitchCheckUsedCar").prop("checked", false);
1628	}
1629
1630	createCarFilterData(dId);
1631	$('#topdeals-clear').trigger('click');
1632};
1633// end banner dropdown selection
1634
1635//Manufacturers
1636
1637// export const handleProductListBannerSelection = async (event) => {
1638// 	event.preventDefault();
1639// 	event.stopPropagation();
1640  
1641// 	// Hide any open popover so it doesn’t override our UI changes
1642// 	$("#product-list-banner-popover").popover("hide");
1643  
1644// 	// Clear any previous selection from all mobile banner items
1645// 	$(".banner-item")
1646// 	  .removeClass("h5 selected")
1647// 	  .addClass("subtitle-bold")
1648// 	  .find("img.check-img")
1649// 	  .addClass("invisible");
1650  
1651// 	const $target = $(event.currentTarget);
1652// 	const mobileBannerChangeId = event.currentTarget.id; // e.g., "banner-easy-leasing"
1653// 	const nid = $target.data("id");                   // e.g., 877
1654// 	const type = $target.data("type");                // e.g., "easy-leasing"
1655// 	const isNidParam = $target.data("identifier") === "tid" ? false : true;
1656  
1657// 	// Set selected state on the clicked banner
1658// 	$target.removeClass("subtitle-bold").addClass("h5 selected");
1659// 	$target.find("img.check-img").removeClass("invisible");
1660  
1661// 	// Get display data
1662// 	let count = $target.find(".count").text();
1663// 	let selectedItem, selectedTitle = "";
1664// 	let dId = "";
1665  
1666// 	if (mobileBannerChangeId === "banner-easy-leasing") {
1667// 	  const data = await pageImage(nid);
1668// 	  selectedItem = data[0].mainImage;
1669// 	  selectedTitle = data[0].title;
1670// 	  dId = "easy-leasing";
1671// 	} else if (mobileBannerChangeId === "banner-top-deal") {
1672// 	  const data = await pageImage(nid);
1673// 	  selectedItem = data[0].mainImage;
1674// 	  selectedTitle = data[0].title;
1675// 	  dId = "top_deals";
1676// 	} else if (mobileBannerChangeId === "banner-green-deal") {
1677// 	  const data = await pageImage(nid);
1678// 	  selectedItem = data[0].mainImage;
1679// 	  selectedTitle = data[0].title;
1680// 	  dId = "green-deals";
1681// 	} else if (mobileBannerChangeId === "banner-" + nid) {
1682// 	  const data = await getPromotionById(nid);
1683// 	  selectedItem = data[0].mainImage;
1684// 	  selectedTitle = data[0].name;
1685// 	  dId = nid;
1686// 	}
1687  
1688// 	if (selectedItem) {
1689// 	  $(".bg-image").css("background-image", "url(" + selectedItem + ")");
1690// 	  $(".dTitleMobile").html(selectedTitle);
1691// 	  $(".dCount").html(count);
1692// 	  $(".dTitleMobile").attr("data-id", dId);
1693// 	  $("#mobileTitle").val(dId);
1694// 	  localStorage.setItem("selectedMobileBannerItem", dId);
1695// 	}
1696  
1697// 	updateQueryStringOnPromotion(type, nid, isNidParam);
1698  
1699// 	// Update any switch controls if needed
1700// 	if (mobileBannerChangeId === "banner-easy-leasing") {
1701// 	  $("#flexSwitchCheckDefaultEasy").prop("checked", true).addClass("disableEasyLeasing");
1702// 	} else {
1703// 	  $("#flexSwitchCheckDefaultEasy").prop("checked", false).removeClass("disableEasyLeasing");
1704// 	}
1705// 	// (Add similar logic for any other switches)
1706  
1707// 	// Trigger the car filter update if needed
1708// 	createCarFilterData(dId);
1709  
1710// 	// Re-render all banner items to ensure the correct one stays selected.
1711// 	const newSelectedMobileBanner = localStorage.getItem("selectedMobileBannerItem");
1712// 	$(".banner-item").each(function () {
1713// 	  const $item = $(this);
1714// 	  if ($item.data("type") === newSelectedMobileBanner) {
1715// 		$item.addClass("h5 selected").removeClass("subtitle-bold");
1716// 		$item.find("img.check-img").removeClass("invisible");
1717// 	  } else {
1718// 		$item.removeClass("h5 selected").addClass("subtitle-bold");
1719// 		$item.find("img.check-img").addClass("invisible");
1720// 	  }
1721// 	});
1722//   };
1723  
1724  
1725
1726export const getBrandList = async () => {
1727	brandListFilter = await get("manufactures");
1728	return brandListFilter;
1729};
1730
1731// car types
1732export const carTypesData = async () => {
1733	carTypes = await get("typeCar");
1734	return carTypes;
1735};
1736
1737//Gear boxes
1738export const gearBoxData = async () => {
1739	transTypes = await get("transType");
1740	return transTypes;
1741};
1742
1743//Fuel types
1744export const fuelTypeData = async () => {
1745	fuelTypes = await get("fuelType");
1746	return fuelTypes;
1747};
1748
1749//modelFamily
1750export const carModelFamilyData = async () => {
1751	carModelFamilyList = await get("getModelFamily");
1752	return carModelFamilyList;
1753};
1754
1755if (document.querySelector("#fuel-type-container") && !window.carDataFetched) {
1756	window.carDataFetched = true;
1757	let carTypeListRow;
1758	carTypeListRow = $("#type-of-car-container");
1759	carList = await carTypesData();
1760	// carTypeListRow.find("li.py-2").remove();
1761	carList.forEach((data) => {
1762		const typeCard = getCarTypeTemplate(data);
1763		$(carTypeListRow).append(typeCard);
1764	});
1765}
1766
1767//to show clear-all-btn if car type is preselected.
1768if (document.querySelector("#type-of-car-filter-button")) {
1769	let checkboxes = document.querySelectorAll('#type-of-car-container input[type="checkbox"]');
1770	let checkedValues = [];
1771	let selectedCarType = [];
1772	let typeOfCars;
1773	const urlParams = new URLSearchParams(window.location.search);
1774
1775	if (urlParams.has("type-of-cars")) {
1776		typeOfCars = urlParams.get("type-of-cars");
1777	}
1778
1779	checkboxes.forEach(function (checkbox) {
1780		if (checkbox.checked) {
1781			checkedValues.push(checkbox.id);
1782			selectedCarType.push(checkbox.value);
1783		}
1784		if (Array.isArray(checkedValues) && checkedValues.length > 0) {
1785			if ($("#filter-clear-all").hasClass("invisible")) {
1786				$("#filter-clear-all").removeClass("invisible");
1787			}
1788			$("#type-of-car-filter-button").addClass("selected");
1789		}
1790	});
1791	if (checkedValues.length > 0) {
1792		updateQueryStringOnFilter("type-of-cars", selectedCarType, false);
1793	}
1794}
1795
1796// for gear box
1797if (document.querySelector("#gear-box-container") && !window.gearDataFetched) {
1798	window.gearDataFetched = true;
1799	let gearBoxTypeListRow;
1800	gearBoxTypeListRow = $("#gear-box-container");
1801	carGear = await gearBoxData();
1802	carGear = Array.from(new Set(carGear.filter((item) => item.label !== "").map((item) => item.label))).map((label) => ({id: label, label: label}));
1803	carGear.forEach((data) => {
1804		const typeGear = getCarTypeTemplate(data);
1805		$(gearBoxTypeListRow).append(typeGear);
1806	});
1807}
1808
1809if (document.querySelector("#fuel-type-container") && !window.fuelDataFetched) {
1810	window.fuelDataFetched = true;
1811	let fuelTypeListRow;
1812	fuelTypeListRow = $("#fuel-type-container");
1813	fuelTypeData().then((data) => {
1814		typeOfFuel = data;
1815
1816		// Split on commas and flatten the list to avoid duplicate fuel types
1817		typeOfFuel = typeOfFuel
1818		.map((item) => item.label.split(",").map((type) => type.trim())) // Split on ',' and trim spaces
1819		.flat(); // Flatten the resulting array to get a list of all individual fuel types
1820
1821		// remove duplicate fuel
1822		typeOfFuel = Array.from(new Set(typeOfFuel)).map((label) => ({
1823            id: label,
1824            label: label,
1825        }));
1826
1827		typeOfFuel.forEach((data) => {
1828			const fuelCard = getCarTypeTemplate(data);
1829			$(fuelTypeListRow).append(fuelCard);
1830		});
1831	});
1832}
1833
1834//mobile filter start here
1835$("#mobile-filter-button").click(async () => {
1836	$("#filterModal").modal("show");
1837	let filterTitle = window.location.href.includes("/en") ? "Filters" : "Φίλτρα";
1838	$("#filterModalLabel")[0].innerText = filterTitle;
1839});
1840
1841//$("#mobile-filter-button").click(async () => {
1842// $("#filterModal").modal("show");
1843
1844//});
1845
1846const getFilterQueryParams = (isFromMonthlyBudget) => {
1847	let value = [];
1848	const queryparams = decodeURIComponent(window.location.href).split("?")[1];
1849	const params = queryparams?.split("/");
1850	const applicableKeys = ["manufacturers", "transmission", "fuel-type", "type-of-cars"];
1851	let pair = null;
1852	let monthlyBudgetMin = "80";
1853	let monthlyBudgetMax = "4500";
1854	params.forEach((d) => {
1855		pair = d.split("=");
1856		const currentKey = pair[0];
1857		if (applicableKeys.includes(currentKey)) {
1858			let paramValue = pair[1].trim();
1859  			let parsedValues;
1860			parsedValues = paramValue.split(",");
1861			value = [...value, ...parsedValues];
1862			// value = [...value, ...JSON.parse(pair[1])];
1863		} else if (currentKey === "monthly-budget") {
1864			// Expecting something like "80,4500"
1865			const parts = pair[1].split(",");
1866			monthlyBudgetMin = parts[0];
1867			monthlyBudgetMax = parts[1];
1868		} 
1869		// else if (currentKey === "monthly_installments_min") {
1870		// 	monthlyBudgetMin = pair[1];
1871		// } else if (currentKey === "monthly_installments_max") {
1872		// 	monthlyBudgetMax = pair[1];
1873		// }
1874	});
1875
1876	if (isFromMonthlyBudget) {
1877		return {
1878			monthlyBudgetMin,
1879			monthlyBudgetMax,
1880		};
1881	}
1882
1883	return value;
1884};
1885
1886  
1887
1888const getFilterPills = (list, classType) => {
1889	let langCode = getLangCode();
1890	// handle through typeOfCar Parameter
1891	/* let tid = "";
1892	const urlParams = new URLSearchParams(window.location.search);
1893	if (!urlParams.has("type")) {
1894		if (urlParams.has("tid")) {
1895			tid = urlParams.get("tid");
1896		}
1897	} */
1898
1899	// const value = getFilterQueryParams() || [];
1900	// let selectedValues = value.map(v => v.toLowerCase());
1901	// selectedValues = translate(classType,selectedValues,"el");
1902
1903	// return list.map((item) => {
1904	// 	if (selectedValues.includes(item.label.toLowerCase())) {
1905	// 		return `<button class="badge selected text-bg-secondary mobile-filter-badge text-body-regular text-avis-mid-grey ${filterClass}" data-label="${item.label}" data-id="${item.id}">${item.label}</button>`;
1906	// 	} else {
1907	// 		return `<button class="badge text-bg-secondary mobile-filter-badge text-body-regular text-avis-mid-grey ${filterClass}" data-label="${item.label}" data-id="${item.id}">${item.label}</button>`;
1908	// 	}
1909	// });
1910	let rawSelectedValues = (getFilterQueryParams() || []).map(v => v.toLowerCase());
1911  
1912  // Now, for each item in the list, we assume item has an id property that holds the raw value.
1913  return list.map((item) => {
1914    // const rawValue = item.label.toLowerCase();
1915	const rawValue = translate(classType,item.label,"json");
1916    // Translate rawValue in the context of the given category (classType)
1917    const displayText = translate(classType, rawValue, langCode) || item.label; // fallback if translate fails
1918
1919    // Mark as selected if the raw value is in the URL’s list
1920    const selectedClass = rawSelectedValues.includes(rawValue) ? "selected" : "";
1921    
1922    return `<button class="badge ${selectedClass} text-bg-secondary mobile-filter-badge text-body-regular text-avis-mid-grey ${classType}" 
1923                data-label="${displayText}" data-id="${item.id}">
1924              ${displayText}
1925            </button>`;
1926  }).join("");
1927};
1928
1929export const getWrapper = (wrapperClass) => {
1930	const wrapper = document.createElement("div");
1931	$(wrapper).addClass(`${wrapperClass} d-flex flex-column gap-3`);
1932	return wrapper;
1933};
1934
1935export const getTitle = (title) => {
1936	return `<h5>${title}</h5>`;
1937};
1938
1939const getBrandsMobileView = (list, isCfg = false, selectedBrands = []) => {
1940	let origin = window.location.origin;
1941
1942	return list.map(({id, src, brandName}) => {
1943		return `<div class="card h-100 border-0 ${!isCfg ? `mobile-brand-filter-item ${selectedBrands && selectedBrands.includes(brandName) && "selected"}` : "manufacturer-item-m text-bg-avis-powder-grey"} py-3" style="cursor: pointer; min-width: 110px;" role="button"
1944    data-id="${id}" data-brandname="${brandName}">
1945    <div class="card-body d-flex flex-column align-items-center justify-content-between py-0 px-1">
1946      <div class="checked-img align-self-end ${!selectedBrands || (selectedBrands && !selectedBrands.includes(brandName) && "invisible")}">
1947        <img src="${origin}/themes/custom/avis2024/images/svg/CheckCircle.svg" class="img-fluid" />
1948      </div>
1949      <div class="brand-logo-wrapper">
1950        <img src="${src}" alt="${brandName}" height="50" class="img-fluid brand-image text-bg-avis-powder-grey" />
1951      </div>
1952      <div class="text-center text-avis-faded-grey text-label p-0 pt-2">${brandName}</div>
1953    </div>
1954  </div>`;
1955	});
1956};
1957
1958//Mobile Viewport Data
1959if (document.querySelector("#mobile-filter-button") && !window.mobileFetched) {
1960	window.mobileFetched = true;
1961	// $("#filterModalLabel")[0].innerText = "Filters";
1962	const modalBody = $("#filterModal .modal-body");
1963	const modalContent = $("#filterModal .modal-content");
1964	let cardListRow;
1965	if ($(".mobile-filter-container").length) {
1966		cardListRow = $(".mobile-filter-container");
1967	} else {
1968		cardListRow = document.createElement("div");
1969		$(cardListRow).addClass(".mobile-filter-container row g-3");
1970
1971		// loopthrough the texonomy
1972		const taxonomyData = [
1973			{
1974				id: "carType",
1975				list: await carTypesData(),
1976			},
1977			{
1978				id: "monthlyBudget",
1979				list: [],
1980			},
1981			{
1982				id: "manufacturer",
1983				list: await getBrandList(),
1984			},
1985			// {
1986			//   id: "model",
1987			//   list: [
1988			//     {
1989			//       id: 1,
1990			//       label: "Audi A1 SportsBack",
1991			//     },
1992			//     {
1993			//       id: 2,
1994			//       label: "Audi A3 Sports Sedan", // Green deals
1995			//     },
1996			//   ],
1997			// },
1998			{
1999				id: "gearBox",
2000				list: await gearBoxData(),
2001			},
2002			{
2003				id: "fuelType",
2004				list: await fuelTypeData(),
2005			},
2006		];
2007
2008		const mainWrapper = document.createElement("div");
2009		$(mainWrapper).addClass("d-flex flex-column spacing-24 mobile-filter-modal");
2010		taxonomyData.forEach((item) => {
2011			const {id, list} = item;
2012			switch (id) {
2013				case "carType": {
2014					if ($(".car-type-filter-wrapper").length) {
2015					} else {
2016						const wrapper = getWrapper("car-type-filter-wrapper");
2017						// 8may
2018						let carFilterTitle = window.location.href.includes("/en") ? "Type of Car" : "Τύπος αυτοκινήτου";
2019						const title = getTitle(carFilterTitle);
2020						const listWrapper = document.createElement("div");
2021						$(listWrapper).addClass("d-flex spacing-12 flex-wrap");
2022						const carData = getFilterPills(list, "type-of-cars");
2023						$(listWrapper).append(carData);
2024						$(wrapper).append(title);
2025						$(wrapper).append(listWrapper);
2026						$(mainWrapper).append(wrapper);
2027					}
2028					break;
2029				}
2030				case "monthlyBudget": {
2031					if ($(".monthly-budget-filter-wrapper").length) {
2032					} else {
2033						const wrapper = getWrapper("monthly-budget-filter-wrapper");
2034						// 8may
2035						let monthFilterTitle = window.location.href.includes("/en") ? "Monthly Budget" : "Μηνιαίο μίσθωμα";
2036						const title = getTitle(monthFilterTitle);
2037						const {monthlyBudgetMin, monthlyBudgetMax} = getFilterQueryParams(true);
2038						const listWrapper = document.createElement("div");
2039						$(listWrapper).addClass("d-flex spacing-12 flex-wrap");
2040						const carData = `<div class="d-flex spacing-12">
2041            <div class="input-group mb-3">
2042              <span class="input-group-text">€</span>
2043              <input id="monthlyBudgetFrom" type="text" class="form-control" aria-label="Amount" min="${monthlyBudgetMin}" value="${monthlyBudgetMin}">
2044            </div>
2045            <div class="input-group mb-3">
2046              <span class="input-group-text">€</span>
2047              <input id="monthlyBudgetTo" type="text" class="form-control" aria-label="Amount" max="${monthlyBudgetMax}" value="${monthlyBudgetMax}">
2048            </div>
2049          </div>`;
2050						$(listWrapper).append(carData);
2051						$(wrapper).append(title);
2052						$(wrapper).append(listWrapper);
2053						$(mainWrapper).append(wrapper);
2054					}
2055					break;
2056				}
2057				case "manufacturer": {
2058					if ($(".manufacturer-filter-wrapper").length) {
2059					} else {
2060						const wrapper = getWrapper("manufacturer-filter-wrapper");
2061						// 8may
2062						let manufacturerFilterTitle = window.location.href.includes("/en") ? "Manufacturer" : "Κατασκευαστής";
2063						const title = getTitle(manufacturerFilterTitle);
2064						const listWrapper = document.createElement("div");
2065						$(listWrapper).addClass("mobile-manufacturer-filter-wrapper d-flex spacing-12 overflow-auto text-bg-avis-powder-grey");
2066						const value = getFilterQueryParams() || [];
2067						const carData = getBrandsMobileView(list, false, value);
2068						$(listWrapper).append(carData);
2069						$(wrapper).append(title);
2070						$(wrapper).append(listWrapper);
2071						$(mainWrapper).append(wrapper);
2072					}
2073					break;
2074				}
2075				case "model": {
2076					const manuFacturerAppliedFilter = $(".manufacturer-filter-wrapper .mobile-brand-filter-item.selected");
2077
2078					const hideClass = manuFacturerAppliedFilter.length ? "" : "d-none";
2079					if ($(".model-filter-wrapper").length) {
2080					} else {
2081						const wrapper = getWrapper(`model-filter-wrapper ${hideClass}`);
2082						//8may
2083						let modalTitle = window.location.href.includes("/en") ? "Model" : "Μοντέλο";
2084						const title = getTitle(modalTitle);
2085						const listWrapper = document.createElement("div");
2086						$(listWrapper).addClass("d-flex spacing-12 flex-wrap");
2087						const carData = getFilterPills(list);
2088						$(listWrapper).append(carData);
2089						$(wrapper).append(title);
2090						$(wrapper).append(listWrapper);
2091						$(mainWrapper).append(wrapper);
2092					}
2093					break;
2094				}
2095				case "gearBox": {
2096					if ($(".gear-box-filter-wrapper").length) {
2097					} else {
2098						const wrapper = getWrapper("gear-box-filter-wrapper");
2099						//8may
2100						let gearFilterTitle = window.location.href.includes("/en") ? "Gearbox" : "Κιβώτιο";
2101						const title = getTitle(gearFilterTitle);
2102						const listWrapper = document.createElement("div");
2103						$(listWrapper).addClass("d-flex spacing-12 flex-wrap");
2104						let listData = Array.from(new Set(list.filter((item) => item.label !== "").map((item) => item.label))).map((label) => ({id: label, label: label}));
2105						const carData = getFilterPills(listData, "transmission");
2106						$(listWrapper).append(carData);
2107						$(wrapper).append(title);
2108						$(wrapper).append(listWrapper);
2109						$(mainWrapper).append(wrapper);
2110					}
2111
2112					break;
2113				}
2114				case "fuelType": {
2115					if ($(".fuel-type-filter-wrapper").length) {
2116					} else {
2117						const wrapper = getWrapper("fuel-type-filter-wrapper");
2118						//8may
2119						let fuelFilterTitle = window.location.href.includes("/en") ? "Fuel Type" : "Τύπος καυσίμου";
2120						const title = getTitle(fuelFilterTitle);
2121
2122						// let typeOfFuel = Array.from(new Set(list.map((item) => item.label))).map((label) => ({
2123						// 	id: label,
2124						// 	label: label,
2125						// }));
2126
2127						// Split on commas, flatten, and remove duplicates
2128						let typeOfFuel = list
2129						.map((item) => item.label.split(",").map((type) => type.trim())) // Split on ',' and trim spaces
2130						.flat(); // Flatten the array to get a list of all individual fuel types
2131
2132						// Remove duplicates by creating a Set and then mapping back to objects
2133						typeOfFuel = Array.from(new Set(typeOfFuel)).map((label) => ({
2134							id: label,
2135							label: label,
2136						}));
2137
2138
2139						const listWrapper = document.createElement("div");
2140						$(listWrapper).addClass("d-flex spacing-12 flex-wrap");
2141						const carData = getFilterPills(typeOfFuel, "fuel-type");
2142						$(listWrapper).append(carData);
2143						$(wrapper).append(title);
2144						$(wrapper).append(listWrapper);
2145						$(mainWrapper).append(wrapper);
2146					}
2147					break;
2148				}
2149				default:
2150					break;
2151			}
2152		});
2153		const brandFooter = getBrandMobileFooterTemplate();
2154		if ($("#filterModal .modal-content .modal-brand-footer").length === 0) {
2155			$(modalContent).append(brandFooter);
2156		}
2157
2158		modalBody.append(mainWrapper);
2159	}
2160}
2161
2162export const handleMobileFilterTagClick = (event) => {
2163	$(event.currentTarget).toggleClass("selected");
2164	const appliedFilterList = filterStatus(false);
2165	setSubtitle(appliedFilterList.length);
2166};
2167
2168export const handleMobileBrandFilterClick = (event) => {
2169	$(event.currentTarget).toggleClass("selected");
2170	$(event.currentTarget).find(".checked-img").toggleClass("invisible");
2171	const manuFacturerAppliedFilter = $(".manufacturer-filter-wrapper .mobile-brand-filter-item.selected");
2172
2173	if (manuFacturerAppliedFilter.length) {
2174		if ($(".model-filter-wrapper")) {
2175			$(".model-filter-wrapper").removeClass("d-none");
2176
2177			// append new data
2178		}
2179	}
2180};
2181
2182export const handleMobileFilterApplyClick = (event, isPageLoad) => {
2183	const mobileAppliedFilters = filterStatus();
2184	$(".delete-icon").removeClass("invisible");
2185	// functioality is removed
2186	/* const filterCount = $(".mobile-filter-count");
2187  filterCount.removeClass("invisible");
2188  filterCount[0].innerText = mobileAppliedFilters.length; */
2189	$(".mobile-applied-filter-wrapper").empty();
2190	if (isPageLoad) {
2191		$(".mobile-applied-filter-wrapper").append(getAppliedFilterTemplate(applyMobileFilterOnLoad()));
2192	} else {
2193		$(".mobile-applied-filter-wrapper").append(getAppliedFilterTemplate(mobileAppliedFilters));
2194	}
2195};
2196
2197const applyMobileFilterOnLoad = () => {
2198	const queryparams = decodeURIComponent(window.location.href).split("?")[1];
2199	const params = queryparams?.split("/");
2200	const applicableKeys = ["manufacturers", "transmission", "fuel-type", "type-of-cars"];
2201	let pair = null;
2202	let arrayList = [];
2203	let monthlyBudgetMin = "80";
2204	let monthlyBudgetMax = "4500";
2205	let lang = getLangCode();
2206	params.forEach((d) => {
2207		pair = d.split("=");
2208		const currentKey = pair[0];
2209		let value = [];
2210
2211		if (applicableKeys.includes(currentKey)) {
2212			let paramValue = pair[1].trim();
2213  			let parsedValues;
2214			parsedValues = paramValue.split(",");
2215			value = [...value, ...parsedValues];
2216			// value = [...value, ...JSON.parse(pair[1])];
2217
2218			if (currentKey === "manufacturers") {
2219				value.forEach((item) => {
2220					arrayList.push({
2221						id: item,
2222						brandname: item,
2223						group: "manufacturer",
2224						label: item.replace(/-([a-z])/g, (_, letter) => ' ' + letter.toUpperCase()),
2225					});
2226				});
2227			} else if (currentKey === "transmission") {
2228				value.forEach((item) => {
2229					arrayList.push({
2230						id: item,
2231						group: "transmission",
2232						label: translate("transmission", item, lang),
2233					});
2234				});
2235			} else if (currentKey === "fuel-type") {
2236				value.forEach((item) => {
2237					arrayList.push({
2238						id: item,
2239						group: "fuel-type",
2240						label: translate("fuel-type", item, lang),
2241					});
2242				});
2243			} else if (currentKey === "type-of-cars") {
2244				value.forEach((item) => {
2245					arrayList.push({
2246						id: item,
2247						group: "type-of-cars",
2248						label: translate("type-of-cars", item, lang),
2249					});
2250				});
2251			}
2252		}else if (currentKey === "monthly-budget") {
2253			// NEW: handle the monthly-budget key
2254			const parts = pair[1].split(",");
2255			monthlyBudgetMin = parts[0];
2256			monthlyBudgetMax = parts[1];
2257		} 
2258		// else if (currentKey === "monthly_installments_min") {
2259		// 	monthlyBudgetMin = pair[1];
2260		// } else if (currentKey === "monthly_installments_max") {
2261		// 	monthlyBudgetMax = pair[1];
2262		// } 
2263		else if (currentKey === "brand") {
2264			arrayList.push({
2265				brandname: pair[1],
2266				group: "manufacturer",
2267				label: pair[1],
2268			});
2269		}
2270	});
2271	arrayList.push({
2272		from: monthlyBudgetMin,
2273		group: "monthlyBudget",
2274		id: "monthlyBudget",
2275		label: `€ ${monthlyBudgetMin} - ${monthlyBudgetMax} `,
2276		to: monthlyBudgetMax,
2277	});
2278
2279	return arrayList;
2280};
2281
2282export const getAppliedFilterTemplate = (filterList, isConfigMobilePills = false) => {
2283	// Get current language code, e.g. "el" or "en"
2284    // const lang = getLangCode();
2285
2286	return filterList.map(({id, label, group}) => {
2287		if (!group) {
2288			return;
2289		}
2290
2291		let origin = window.location.origin;
2292		return `<div
2293    class="badge text-bg-powder-grey text-avis-mid-grey mobile-filter-applied-badge d-flex gap-2 justify-content-center align-items-center px-3 py-2">
2294    <div>${label}</div>
2295    <button type="button" class='btn border-0 p-0 text-bg-avis-faded-grey ${isConfigMobilePills && "js-remove-mobile-filter-cfg"} remove-mobile-filter' data-id="${id}" data-group="${group}" data-label="${label}">
2296    <img src="${origin}/themes/custom/avis2024/images/svg/X.svg" alt='remove-filter' data-id="${id}" data-group="${group}" /></button>
2297  </div>`;
2298	});
2299};
2300
2301export const setSubtitle = (count, total) => {
2302	const subTitleText = $(".filter-subtitle-text");
2303	if ($(subTitleText).hasClass("invisible")) {
2304		$(subTitleText).removeClass("invisible");
2305	}
2306
2307	subTitleText[0].innerText = `${count} filter selected, ${total} matching vehicles`;
2308};
2309
2310const filterStatus = () => {
2311	// mobile-filter-modal
2312	const carTypeAppliedFilter = $(".car-type-filter-wrapper .mobile-filter-badge.selected");
2313	const monthlyBudgetFromVal = $("#monthlyBudgetFrom").val();
2314	const monthlyBudgetToVal = $("#monthlyBudgetTo").val();
2315	const manuFacturerAppliedFilter = $(".manufacturer-filter-wrapper .mobile-brand-filter-item.selected");
2316	const modelAppliedFilter = $(".model-filter-wrapper .mobile-filter-badge.selected");
2317	const gearBoxAppliedFilter = $(".gear-box-filter-wrapper .mobile-filter-badge.selected");
2318	const fuelTypeAppliedFilter = $(".fuel-type-filter-wrapper .mobile-filter-badge.selected");
2319	const carList = [];
2320	const brandList = [];
2321	const modelList = [];
2322	const gearList = [];
2323	const fuelList = [];
2324	let monthlyBudget = [];
2325	if (monthlyBudgetFromVal && monthlyBudgetToVal) {
2326		monthlyBudget = [
2327			{
2328				from: monthlyBudgetFromVal,
2329				to: monthlyBudgetToVal,
2330				id: "monthlyBudget",
2331				group: "monthlyBudget",
2332				label: `€ ${monthlyBudgetFromVal}-${monthlyBudgetToVal}`,
2333			},
2334		];
2335	}
2336
2337	carTypeAppliedFilter.each((index, element) => {
2338		const listData = {...$(element).data(), group: "type-of-cars"};
2339		carList.push(listData);
2340	});
2341
2342	manuFacturerAppliedFilter.each((index, element) => {
2343		const dataAttribute = $(element).data();
2344		const listData = {
2345			...dataAttribute,
2346			label: dataAttribute.brandname,
2347			group: "manufacturer",
2348		};
2349		brandList.push(listData);
2350	});
2351
2352	modelAppliedFilter.each((index, element) => {
2353		const listData = {...$(element).data(), group: "model"};
2354		modelList.push(listData);
2355	});
2356
2357	gearBoxAppliedFilter.each((index, element) => {
2358		const listData = {...$(element).data(), group: "transmission"};
2359		gearList.push(listData);
2360	});
2361
2362	fuelTypeAppliedFilter.each((index, element) => {
2363		const listData = {...$(element).data(), group: "fuel-type"};
2364		fuelList.push(listData);
2365	});
2366	const mobileSelectedFilters = [...carList, ...monthlyBudget, ...brandList, ...modelList, ...gearList, ...fuelList];
2367
2368	return mobileSelectedFilters;
2369};
2370
2371// brand preselect mobile
2372if (document.querySelector("#mobile-filter-button")) {
2373	let manufacturer_value = $("#mobileTitle").val();
2374	if (manufacturer_value) {
2375		const urlParams = getQueryParamsFromSlash(window.location.search);
2376		    // Retrieve manufacturer parameter (try both keys)
2377			let manufacturersParam = urlParams.get("manufacturers") || urlParams.get("brand");
2378			if (manufacturersParam) {
2379			  // Normalize: lowercase, replace dashes with spaces, and split on comma
2380			  const manufacturerList = manufacturersParam
2381				.toLowerCase()
2382				.replace(/-/g, " ")
2383				.split(",")
2384				.map(item => item.trim());
2385			  
2386			  const itemList = $(".mobile-brand-filter-item");
2387			  itemList.each((index, element) => {
2388				const elementBrand = $(element).data("brandname").toLowerCase().replace(/-/g, " ");
2389				if (manufacturerList.includes(elementBrand)) {
2390				  makeActive(element);
2391				  $(element).find(".checked-img").removeClass("invisible");
2392				}
2393			  });
2394			}
2395		  }
2396	loadDictionary()
2397	.then(() => { 
2398		handleMobileFilterApplyClick(null, true);
2399	});
2400}
2401// end brand preselect mobile
2402
2403// close button click
2404// $(".mobile-filter-modal-wrapper .filterModal-close-btn").click(() => {
2405//   clearMobileFilter;
2406// });
2407
2408const clearMobileFilter = () => {
2409	if (mobileAppliedFilters.length === 0) {
2410		handleMobileFilterCancelClick();
2411	} else {
2412		const groupByType = mobileAppliedFilters.reduce((acc, value) => {
2413			// Group initialization
2414			if (!acc[value.group]) {
2415				acc[value.group] = [];
2416			}
2417
2418			// Grouping
2419			acc[value.group].push(value);
2420
2421			return acc;
2422		}, {});
2423
2424		let monthlybudget = false;
2425
2426		Object.keys(groupByType).forEach((key) => {
2427			monthlybudget = key === "monthlyBudget" ? true : false;
2428			const groupData = groupByType[key];
2429			const idList = groupData.map((item) => item.id);
2430			switch (key) {
2431				case "carType": {
2432					const carTypeAppliedFilter = $(".car-type-filter-wrapper .mobile-filter-badge.selected");
2433					// create single funtion and make it dynamic
2434					$(carTypeAppliedFilter).each((index, element) => {
2435						const elementId = $(element).data("id");
2436						if (!idList.includes(elementId)) {
2437							revmoveSelected(element);
2438						}
2439					});
2440					break;
2441				}
2442				case "manufacturer": {
2443					const manuFacturerAppliedFilter = $(".manufacturer-filter-wrapper .mobile-brand-filter-item.selected");
2444					$(manuFacturerAppliedFilter).each((index, element) => {
2445						const elementId = $(element).data("id");
2446						if (!idList.includes(elementId)) {
2447							const checkClass = $(element).find(".checked-img");
2448							if (!$(checkClass).hasClass("invisible")) {
2449								$(checkClass).addClass("invisible");
2450							}
2451							revmoveSelected(element);
2452						}
2453					});
2454					break;
2455				}
2456				case "model": {
2457					const modelAppliedFilter = $(".model-filter-wrapper .mobile-filter-badge.selected");
2458					$(modelAppliedFilter).each((index, element) => {
2459						const elementId = $(element).data("id");
2460						if (!idList.includes(elementId)) {
2461							revmoveSelected(element);
2462						}
2463					});
2464					break;
2465				}
2466				case "transmission": {
2467					const gearBoxAppliedFilter = $(".gear-box-filter-wrapper .mobile-filter-badge.selected");
2468					$(gearBoxAppliedFilter).each((index, element) => {
2469						const elementId = $(element).data("id");
2470						if (!idList.includes(elementId)) {
2471							revmoveSelected(element);
2472						}
2473					});
2474					break;
2475				}
2476				case "fuel-type": {
2477					const fuelTypeAppliedFilter = $(".fuel-type-filter-wrapper .mobile-filter-badge.selected");
2478					$(fuelTypeAppliedFilter).each((index, element) => {
2479						const elementId = $(element).data("id");
2480						if (!idList.includes(elementId)) {
2481							revmoveSelected(element);
2482						}
2483					});
2484					break;
2485				}
2486				case "monthlyBudget": {
2487					// set monthly bug=dget correct value
2488					$("#monthlyBudgetFrom").val("80");
2489					$("#monthlyBudgetTo").val("4500");
2490					break;
2491				}
2492				default:
2493					break;
2494			}
2495		});
2496		if (!monthlybudget) {
2497			$("#monthlyBudgetFrom").val("80");
2498			$("#monthlyBudgetTo").val("4500");
2499		}
2500		setSubtitle(mobileAppliedFilters.length);
2501	}
2502};
2503
2504// $(".mobile-filter-modal-wrapper").on(
2505//   "click",
2506//   ".filterModal-close-btn",
2507//   clearMobileFilter
2508// );
2509
2510export const handleMobileFilterCancelClick = (event) => {
2511	const carTypeAppliedFilter = $(".car-type-filter-wrapper .mobile-filter-badge.selected");
2512
2513	$(carTypeAppliedFilter).each((index, element) => {
2514		revmoveSelected(element);
2515	});
2516
2517	const manuFacturerAppliedFilter = $(".manufacturer-filter-wrapper .mobile-brand-filter-item.selected");
2518
2519	$(manuFacturerAppliedFilter).each((index, element) => {
2520		const checkClass = $(element).find(".checked-img");
2521		if (!$(checkClass).hasClass("invisible")) {
2522			$(checkClass).addClass("invisible");
2523		}
2524		revmoveSelected(element);
2525	});
2526
2527	const modelAppliedFilter = $(".model-filter-wrapper .mobile-filter-badge.selected");
2528
2529	$(modelAppliedFilter).each((index, element) => {
2530		revmoveSelected(element);
2531	});
2532
2533	const gearBoxAppliedFilter = $(".gear-box-filter-wrapper .mobile-filter-badge.selected");
2534
2535	$(gearBoxAppliedFilter).each((index, element) => {
2536		revmoveSelected(element);
2537	});
2538	const fuelTypeAppliedFilter = $(".fuel-type-filter-wrapper .mobile-filter-badge.selected");
2539
2540	$(fuelTypeAppliedFilter).each((index, element) => {
2541		revmoveSelected(element);
2542	});
2543	$("#monthlyBudgetFrom").val("80");
2544	$("#monthlyBudgetTo").val("4500");
2545	$(".filter-subtitle-text").addClass("invisible");
2546	mobileAppliedFilters = [];
2547	$(".delete-icon").addClass("invisible");
2548	/*  const filterCount = $('.mobile-filter-count');
2549  filterCount[0].innerText = 0;
2550  filterCount.addClass('invisible'); */
2551	$(".mobile-applied-filter-wrapper").empty();
2552	updateQueryStringOnFilter(null, null, true);
2553	//createCarFilterData();
2554};
2555
2556$(".filter-floating-button .delete-icon").click((event) => {
2557	handleMobileFilterCancelClick();
2558});
2559
2560//mobile filters change on 7th may
2561// $(document).on("click", ".remove-mobile-filter", handleMobileFilterCancelClick);
2562
2563export const handleMobileFilterRemoveClick = (event) => {
2564    return new Promise((resolve, reject) => {
2565        try {
2566            const label = $(event.currentTarget).data("label");
2567            const group = $(event.currentTarget).data("group");
2568
2569            const $carType = $(".car-type-filter-wrapper .mobile-filter-badge.selected");
2570            const $manufacturer = $(".manufacturer-filter-wrapper .mobile-brand-filter-item.selected");
2571            const $modelAppliedFilter = $(".model-filter-wrapper .mobile-filter-badge.selected");
2572            const $gearBox = $(".gear-box-filter-wrapper .mobile-filter-badge.selected");
2573            const $fuelType = $(".fuel-type-filter-wrapper .mobile-filter-badge.selected");
2574
2575            if (group === "manufacturer") {
2576                $manufacturer.each((index, element) => {
2577                    if ($(element).data("brandname") === label) {
2578                        $(element).removeClass("selected");
2579                        $(element).find(".checked-img").toggleClass("invisible");
2580                    }
2581                });
2582                $modelAppliedFilter.removeClass("selected");
2583            } else if (group === "model") {
2584                $modelAppliedFilter.each((index, element) => {
2585                    if ($(element).data("label") === label) {
2586                        $(element).removeClass("selected");
2587                    }
2588                });
2589            } else if (group === "monthlyBudget") {
2590                $("#monthlyBudgetFrom").val("80");
2591                $("#monthlyBudgetTo").val("4500");
2592            } else if (group === "transmission") {
2593                $gearBox.each((index, element) => {
2594                    if ($(element).data("label") === label) {
2595                        $(element).removeClass("selected");
2596                    }
2597                });
2598            } else if (group === "fuel-type") {
2599                $fuelType.each((index, element) => {
2600                    if ($(element).data("label") === label) {
2601                        $(element).removeClass("selected");
2602                    }
2603                });
2604            } else if (group === "type-of-cars") {
2605                $carType.each((index, element) => {
2606                    if ($(element).data("label") === label) {
2607                        $(element).removeClass("selected");
2608                    }
2609                });
2610            }
2611
2612            handleMobileFilterApplyClick();
2613            createCarFilterData(null, true);
2614
2615            resolve(); // Resolve the promise once all operations are complete
2616        } catch (error) {
2617            reject(error); // Reject the promise if there's an error
2618        }
2619    });
2620};
2621
2622$(document).on("click", ".remove-mobile-filter", function(event) {
2623    handleMobileFilterRemoveClick(event).then(() => {
2624        metaTags(getLangCode());
2625    }).catch((error) => {
2626        console.error("Error handling mobile filter remove click:", error);
2627    });
2628});
2629
2630//end
2631
2632// brand selection
2633
2634export const toggleBrandSelection = (event) => {
2635	if (!$(event.currentTarget).parents().hasClass("filter-brand-container")) {
2636		removeActive();
2637		makeActive(event.currentTarget);
2638	} else {
2639		if ($(event.currentTarget).hasClass("selected")) {
2640			$(event.currentTarget).removeClass("selected");
2641		} else {
2642			makeActive(event.currentTarget);
2643		}
2644		$("#filter-brand-save-button").removeAttr("disabled");
2645	}
2646};
2647
2648export const toggleConfiguratorBrandSelection = (event) => {
2649	if (!$(event.currentTarget).parents().hasClass("filter-brand-container")) {
2650		removeActive();
2651		makeActive(event.currentTarget);
2652	} else {
2653		if ($(event.currentTarget).hasClass("selected")) {
2654			$(event.currentTarget).removeClass("selected");
2655		} else {
2656			makeActive(event.currentTarget);
2657		}
2658		$("#filter-brand-save-button").removeAttr("disabled");
2659	}
2660};
2661
2662export const toggleConfiguratorListBrandSelection = (event) => {
2663	if (!$(event.currentTarget).parents().hasClass("brandModalConfiguratorListing")) {
2664		makeActive(event.currentTarget);
2665	} else {
2666		if ($(event.currentTarget).hasClass("selected")) {
2667			$(event.currentTarget).removeClass("selected");
2668		} else {
2669			makeActive(event.currentTarget);
2670		}
2671		$("#filter-brand-save-button").removeAttr("disabled");
2672	}
2673};
2674
2675
2676const renderAvailableCars = (filteredBrands) => {
2677	$("#brandModalConfiguratorListing").modal("show");
2678	const modalBody = $("#brandModalConfiguratorListing .modal-body");
2679	const cardListRow = document.createElement("div");
2680	$(cardListRow).addClass("brand-container row g-3 scrollbar-style-large");
2681	filteredBrands?.forEach((data) => {
2682		const brandCard = getConfiguratorBrandTileData(data);
2683		$(cardListRow).append(brandCard);
2684	});
2685	modalBody.html(cardListRow);
2686	// $(".brand-container .brand-item").removeClass('selected');
2687	// $('.brand-container > div:first-of-type').find(".brand-item").removeClass('selected');
2688	const currentSelectedBrand = JSON.parse(localStorage.getItem("selectedCarBrand"));
2689	currentSelectedBrand && !window.clearFilterCalled && $(".brand-container .brand-item[data-brandname=" + currentSelectedBrand.carName + "]").addClass("selected");
2690};
2691
2692export const getCarBrands = async (evt, isMobile) => {
2693	evt.stopPropagation();
2694	var currentCarType = isMobile ? $(evt.currentTarget).data("label") : $(evt.currentTarget).val();
2695	let typeCars = [];
2696	typeCars = await getCars("manufacturers/" + currentCarType, "");
2697	const filteredCarsBrands = getCarsByType(typeCars?.[0]);
2698
2699	if (isMobile) {
2700		const $mobileManufacturerFilterWrapper = $(".manufacturer-container-m");
2701		$mobileManufacturerFilterWrapper.empty();
2702		const carData = getBrandsMobileView(filteredCarsBrands, isMobile, selectedBrands);
2703		$mobileManufacturerFilterWrapper.html(carData);
2704	}	else {
2705		renderAvailableCars(filteredCarsBrands);
2706		localStorage.setItem("selectedVehicleType", currentCarType);
2707		// clearing selection on switch
2708		$(".brand-items").removeClass("selected");
2709	}
2710};
2711
2712// $(document).on("change.car", "input[name='inlineCarRadioOptions']", getCarBrands);
2713
2714export const applyFilterBtnConfigurator = (event) => {
2715	if (event?.preventDefault) {
2716		event.preventDefault();
2717	}
2718
2719	postFiltersData();
2720
2721	// if (event?.target) {
2722	// 	$(event.target).closest("ul").prev().dropdown("toggle");
2723	// }
2724
2725	const fromVal = $("#monthlyBudgetRangeFrom").val();
2726	const toVal = $("#monthlyBudgetRangeTo").val();
2727	$("#config-monthly-budget-dropdown").text(`${fromVal} - ${toVal} €`).addClass("selected");
2728	window.clearFilterCalled = false;
2729	$("#config-filter-clear-all").removeClass("invisible").addClass("visible");
2730	//updated for monthly dropdown text - to be moved somewhere later
2731};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.