var base_url = "https://www.testyournext.com";
if (base_url != window.location.origin) {
	base_url = window.location.origin;
	if (base_url == "http://127.0.0.1")
		base_url += "/ebikebox/TYB";
}
(function () {
	// 'use strict';
	$.expr[":"].contains = $.expr.createPseudo(function(arg) {
		return function( elem ) {
			return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
		};
	});
	window.redirectWithCoordinates = function (baseUrl) {
    let lat = sessionStorage.getItem("latitude");
    let lon = sessionStorage.getItem("longitude");
    let url = baseUrl;
    if (lat && lon) {
        url += "?latitude=" + encodeURIComponent(lat) + "&longitude=" + encodeURIComponent(lon);
    }
    window.location.href = url;
};
	function generateOutPutDate(toconvert) {
		var outputdate = "'" + with_leading_zeros(toconvert.getDate()) + "." + with_leading_zeros(toconvert.getMonth() + 1) + "." + toconvert.getFullYear() + " " + with_leading_zeros(toconvert.getHours()) + ":" + with_leading_zeros(toconvert.getMinutes()) + "'";
		return outputdate;
	}
	Date.prototype.addHours = function (h) {
		this.setTime(this.getTime() + (h * 60 * 60 * 1000));
		return this;
	}
	Date.prototype.addDays = function (d) {
		this.setTime(this.getTime() + (d * 24 * 60 * 60 * 1000));
		return this;
	}
	if($("#seat_height_min").length > 0)
	{
	document.addEventListener('DOMContentLoaded', function () {
    // Funktion zum Aktualisieren der Sitzhöhe-Werte
    window.updateSeatHeightValue = function (type, value) {
        document.getElementById(`seat_height_${type}-value`).textContent = value;
    };
    // Initialisiere die Anzeige beim Laden der Seite
    updateSeatHeightValue('min', document.getElementById('seat_height_min').value);
    updateSeatHeightValue('max', document.getElementById('seat_height_max').value);
});
}
$(document).ready(function () {
    // Standort aus Session holen (falls vorhanden)
    let savedLocation = sessionStorage.getItem("selectedLocation");
    let savedLat = sessionStorage.getItem("latitude");
    let savedLon = sessionStorage.getItem("longitude");
    if (savedLocation && savedLat && savedLon) {
        $("#location-input").hide();
        $("#selected-location").show();
        $("#confirm-location").hide();
        $("#selected-location-text").text(savedLocation);
        $("#latitude").val(savedLat);
        $("#longitude").val(savedLon);
    } else {
        $("#clear-location").hide();
    }
    // PLZ-Suche
    $("#zip-search").on("input", function () {
        let query = $(this).val().trim();
        let resultsList = $("#zip-results");
        if (query.length < 2) {
            resultsList.hide();
            return;
        }
        $.ajax({
            url: base_url + "/bi/searchZipLocations",
            method: "GET",
            data: { query: query },
            success: function (data) {
                let locations = JSON.parse(data);
                resultsList.empty().show();
                if (locations.length === 0) {
                    resultsList.append("
Keine Treffer");
                    return;
                }
                locations.forEach(function (location) {
                    let listItem = $("")
                        .text(`${location.c_zip} ${location.c_locationname} (${location.c_country_code})`)
                        .data("latitude", location.c_latitude)
                        .data("longitude", location.c_longitude)
                        .css({ cursor: "pointer", padding: "5px", borderBottom: "1px solid #ddd" })
                        .hover(
                            function () { $(this).css("background", "#f0f0f0"); },
                            function () { $(this).css("background", ""); }
                        )
                        .click(function () {
                            let selectedText = $(this).text();
                            let lat = $(this).data("latitude");
                            let lon = $(this).data("longitude");
                            $("#zip-search").val(selectedText);
                            $("#latitude").val(lat);
                            $("#longitude").val(lon);
                            sessionStorage.setItem("selectedLocation", selectedText);
                            sessionStorage.setItem("latitude", lat);
                            sessionStorage.setItem("longitude", lon);
                            $("#location-input").hide();
                            $("#selected-location").show();
                            $("#selected-location-text").text(selectedText);
                            resultsList.hide();
                            // Filterseite mit Koordinaten neu laden
                            const queryParams = new URLSearchParams(window.location.search);
                            queryParams.set("latitude", lat);
                            queryParams.set("longitude", lon);
                            window.location.search = queryParams.toString();
                        });
                    resultsList.append(listItem);
                });
            },
            error: function () {
                resultsList.empty().append("Fehler beim Abrufen der Daten").show();
            }
        });
    });
    // Standort löschen
    $("#clear-location").click(function () {
        sessionStorage.removeItem("selectedLocation");
        sessionStorage.removeItem("latitude");
        sessionStorage.removeItem("longitude");
        $("#confirm-location").show();
        $("#selected-location").hide();
        $("#location-input").show();
        $("#zip-search").val("");
        $("#latitude").val("");
        $("#longitude").val("");
    });
    // Standort bestätigen (Latitude/Longitude wird für den Filter übernommen)
    $("#confirm-location").click(function () {
        let lat = $("#latitude").val();
        let lon = $("#longitude").val();
        if (!lat || !lon) {
            alert("Bitte einen Standort auswählen.");
            return;
        }
        // Filterseite mit Koordinaten neu laden
        const queryParams = new URLSearchParams(window.location.search);
        queryParams.set("latitude", lat);
        queryParams.set("longitude", lon);
        window.location.search = queryParams.toString();
    });
    // Funktion zum Laden der aktiven Filter
    function loadSelectedFilters() {
        const params = new URLSearchParams(window.location.search);
        const filterContainer = $("#selected-filters");
        filterContainer.empty();
        let hasFilters = false;
        params.forEach((value, key) => {
            if (key !== "latitude" && key !== "longitude") {
                hasFilters = true;
                let filterTag = $("")
                    .addClass("filter-tag")
                    .text(`${key}: ${value}`)
                    .append(
                        $("")
                            .addClass("remove-filter")
                            .html('')
                            .css({ marginLeft: "5px", cursor: "pointer" })
                            .click(function () {
                                params.delete(key);
                                window.location.search = params.toString();
                            })
                    );
                filterContainer.append(filterTag);
            }
        });
        if (hasFilters) {
            $("#selected-filters-container").show();
        } else {
            $("#selected-filters-container").hide();
        }
    }
    // Filter anwenden
    $("#apply-filters").click(function () {
        const filters = {};
        let seatHeightModified = false;
        $("input[name]").each(function () {
            const filterName = $(this).attr("name");
            if (($(this).is(":checked") || $(this).attr("type") === "range")) {
                if ($(this).attr("type") === "checkbox") {
                    if (!filters[filterName]) {
                        filters[filterName] = [];
                    }
                    filters[filterName].push($(this).val());
                } else if ($(this).attr("type") === "range") {
                    const defaultMin = $(this).attr("min");
                    const defaultMax = $(this).attr("max");
                    if ((filterName.includes('min') && $(this).val() != defaultMin) || 
                        (filterName.includes('max') && $(this).val() != defaultMax)) {
                        seatHeightModified = true;
                    }
                }
            }
        });
        if (seatHeightModified) {
            const minInput = $("input[name='seat_height_min']").val();
            const maxInput = $("input[name='seat_height_max']").val();
            filters['seat_height_min'] = minInput;
            filters['seat_height_max'] = maxInput;
        }
        // Falls Standort gespeichert, Koordinaten hinzufügen
        const savedLat = sessionStorage.getItem("latitude");
        const savedLon = sessionStorage.getItem("longitude");
        if (savedLat && savedLon) 
		{
            filters['latitude'] = savedLat;
            filters['longitude'] = savedLon;
        }
        const queryParams = new URLSearchParams();
        for (const key in filters)
		{
            queryParams.append(key, Array.isArray(filters[key]) ? filters[key].join(",") : filters[key]);
        }
        window.location.search = queryParams.toString();
    });
    // Filter anzeigen nach dem Laden der Seite
    loadSelectedFilters();
    // Suchergebnis-Liste ausblenden, wenn außerhalb geklickt wird
    $(document).click(function (e) {
        if (!$(e.target).closest("#zip-search, #zip-results").length) {
            $("#zip-results").hide();
        }
    });
});
	function initTimeSelection() {
		//    alert(hoursdisabled_cat);
		var currentdate = new Date();
		var currentdate_before = new Date();
		if ($("#bike_search_from").attr('data-beforetoday-hours')) {
			currentdate_before = currentdate_before.addHours(-1 * parseInt($("#bike_search_from").attr('data-beforetoday-hours')));
		}
		if ($("#bike_search_from").attr('data-beforetoday-days')) {
			currentdate_before = currentdate_before.addDays(-1 * parseInt($("#bike_search_from").attr('data-beforetoday-days')));
		}
		var outputdate = generateOutPutDate(currentdate);
		var outputdate_before = generateOutPutDate(currentdate_before);
		if ($("#bike_search_from").attr('date-startdate')) {
			outputdate_before = outputdate = $("#bike_search_from").attr("date-startdate");// generateOutPutDate($("#bike_search_from").attr("date-startdate"));
		}
		/*
				var currentdate = new Date();
				var currentdate_before = new Date();
				if ($("#bike_search_from").attr('data-beforetoday-hours')) {
					currentdate_before = currentdate_before.addHours(-1 * parseInt($("#bike_search_from").attr('data-beforetoday-hours')));
				}
				if ($("#bike_search_from").attr('data-beforetoday-days')) {
					currentdate_before = currentdate_before.addDays(-1 * parseInt($("#bike_search_from").attr('data-beforetoday-days')));
				}
				var outputdate = generateOutPutDate(currentdate);
				var outputdate_before = generateOutPutDate(currentdate_before);
		*/
		if ($('#bike_search_from').length > 0) {
			$('#bike_search_from').datetimepicker({
				minView: 1,
				autoclose: true,
				language: 'de',
				weekStart: 1,
				format: 'dd.mm.yyyy hh:ii',
				outputformat: 'dd.mm.yyyy hh:00',
				startDate: outputdate_before, //outputdate,
				todayBtn: 1,
				//   hoursDisabled: [0, 1, 2, 3, 4, 5, 6, 7, 21, 22, 23, 24],
				todayHighlight: 1,
				pickerPosition: "container-left",
				startView: 2,
				minuteStep: 60,
				forceParse: 1,
				showMeridian: 0,
				//linkField: "bike_search_until",
				linkFormat: "dd.mm.yyyy hh:ii",
				icons: {
					time: "fa fa-clock-o",
					date: "fa fa-calendar",
					up: "fa fa-arrow-up",
					down: "fa fa-arrow-down"
				}
			});
			$('#bike_search_until').datetimepicker({
				language: 'de',
				weekStart: 1,
				format: 'dd.mm.yyyy hh:ii',
				outputformat: 'dd.mm.yyyy hh:00',
				startDate: outputdate,
				todayBtn: 1,
				// hoursDisabled: [0, 1, 2, 3, 4, 5, 6, 7, 21, 22, 23, 24],
				autoclose: 1,
				todayHighlight: 1,
				pickerPosition: "container-left",
				startView: 2,
				minView: 1,
				minuteStep: 60,
				forceParse: 1,
				showMeridian: 0,
				icons: {
					time: "fa fa-clock-o",
					date: "fa fa-calendar",
					up: "fa fa-arrow-up",
					down: "fa fa-arrow-down"
				}
			});
			$('.form_datetime[data-readonly="1"] input').css('cursor', 'pointer').attr('disabled', 'disabled');
			$('.form_datetime[data-readonly="1"]').on('click', function () {
				$(this).find('.input-group-addon').trigger('click');
			});
			$('#bike_search_from').datetimepicker().on('changeDate', function (e) {
				var first = new Date(e.date.setMinutes(0));
			//	console.log($("#bike_search_until").attr('data-minspan-hours'));
				if ($("#bike_search_until").attr('data-minspan-hours')) {
					first = first.addHours(parseInt($("#bike_search_until").attr('data-minspan-hours')));
				}
				//console.log(first);
				if ($("#bike_search_until").attr('data-minspan-days')) {
					first = first.addDays(parseInt($("#bike_search_until").attr('data-minspan-days')));
				}
				$("#bike_search_until").datetimepicker('setDate', first);
				$("#bike_search_until").datetimepicker('setStartDate', generateOutPutDate(first));
			});
			$('#bike_search_from').datetimepicker().on('outOfRange', function (e) {
			});
			$('#bike_search_until').datetimepicker().on('changeDate', function (e) {
				$("#form_search_bikes_submit").trigger("click");
//OLD TYPE
// $("#form_search_bikes").submit();
			});
		}
		/*
				//    alert(hoursdisabled_cat);
				var currentdate = new Date();
				outputdate = generateOutPutDate(currentdate);
				if ($('#bike_search_from').length > 0) {
					//alert($("#bike_search_from").attr("date-startdate"));
					outputdate = $("#bike_search_from").attr("date-startdate");// generateOutPutDate($("#bike_search_from").attr("date-startdate"));
					$('#bike_search_from').datetimepicker({
						minView: 1,
						autoclose: true,
						language: 'de',
						weekStart: 1,
						format: 'dd.mm.yyyy hh:ii',
						outputformat: 'dd.mm.yyyy hh:00',
						startDate: outputdate, //outputdate,
						todayBtn: 1,
						//    hoursDisabled: [0, 1, 2, 3, 4, 5, 6, 7, 21, 22, 23, 24],
						todayHighlight: 1,
						pickerPosition: "container-left",
						startView: 2,
						minuteStep: 60,
						forceParse: 1,
						showMeridian: 0,
						linkField: "bike_search_until",
						linkFormat: "dd.mm.yyyy hh:ii",
						icons: {
							time: "fa fa-clock-o",
							date: "fa fa-calendar",
							up: "fa fa-arrow-up",
							down: "fa fa-arrow-down"
						}
					});
					$('#bike_search_until').datetimepicker({
						language: 'de',
						weekStart: 1,
						format: 'dd.mm.yyyy hh:ii',
						outputformat: 'dd.mm.yyyy hh:00',
						startDate: outputdate,
						todayBtn: 1,
						// hoursDisabled: [0, 1, 2, 3, 4, 5, 6, 7, 21, 22, 23, 24],
						autoclose: 1,
						todayHighlight: 1,
						pickerPosition: "container-left",
						startView: 2,
						minView: 1,
						minuteStep: 60,
						forceParse: 1,
						showMeridian: 0,
						icons: {
							time: "fa fa-clock-o",
							date: "fa fa-calendar",
							up: "fa fa-arrow-up",
							down: "fa fa-arrow-down"
						}
					});
					$('#bike_search_from').datetimepicker().on('changeDate', function (e) {
						//         var first = new Date(e.date.setMinutes(0));
						//      first.setHours(first.getHours()+first.getTimezoneOffset()/60); //timezone correction
						//    console.log(first);
						// alert("changed");
						//    $("#bike_search_until").datetimepicker('setStartDate', generateOutPutDate(first));
					});
					$('#bike_search_from').datetimepicker().on('outOfRange', function (e) {
					});
					$('#bike_search_until').datetimepicker().on('changeDate', function (e) {
						//   $("#form_search_bikes").submit();
					});
				}
		*/
	}
	function with_leading_zeros(value) {
		return (value < 10 ? '0' : '') + value;
	}
	function initCartButtons() {
		$("#cart #cart-content .button-removefromcart").click(function () {
			//  console.log("REMOVE");
			//      alert("REMOVE");
			var pid = $(this).attr("pid");
			var for_pid = $(this).attr("for_pid");
			//  console.log("remove3 " + pid + " fp:" + for_pid);
			//  alert("Remove " + pid + " " + for_pid);
			$.ajax({
				url: base_url + "/cart/remove",
				method: "POST", //First change type to method here
				data: {
					product_id: pid,
					for_product_id: for_pid,
				},
				success: function (response) {
					productsincart = getProductsInCart(response);
					//    alert("Responsge success" + pid + " " + for_pid);
					response = getCartResult(response);
					$("#cart-content").html(response);
					self.location.reload();
					initCartButtons();
					updateCartNotification(productsincart);
				},
				error: function () {
					//  alert("error");
				}
			});
			//   alert("Remove done " + pid + " " + for_pid);
		});
	}
	function check_username(value) {
//console.log("CHECK USERNAME");
		Cookies.set("nocache", 1, {expires: 1});
		$.ajax({
			url: base_url + '/data/checkUserperMail',
			method: "POST", //First change type to method here
			data: {
				email: value, // Second add quotes on the value.
			},
			success: function (resp) {
				//   alert('in success JSON');
				//console.log(resp.response)
				if (resp == "1") {
					document.getElementById("e-mail-info").style.display = "block";
					//$("#e-mail-info").show();
					//   $("#customer-information .button-next").hide();
				}
			},
			error: function (resp) {
			}
		});
	}
	function validateCustomerInfo(firstrun = false) {
//console.log("Validate");
		valid = true;
		zip = $("#zip")[0].value;
		street = $("#street")[0].value;
		town = $("#town")[0].value;
		phone = $("#phone")[0].value;
		mail = $("#email")[0].value;
		firstname = $("#firstname")[0].value;
		lastname = $("#lastname")[0].value;
		$('#customer-information input').removeClass("error");
		if (mail.length < 6 || !isEmail(mail)) {
			valid = false;
			if (!firstrun)
				$("#email").addClass("error");
		}
		if (firstname.length < 2) {
			valid = false;
			if (!firstrun)
				$("#firstname").addClass("error");
		}
		if (lastname.length < 2) {
			valid = false;
			if (!firstrun)
				$("#lastname").addClass("error");
		}
		//  console.log("street: " + street.length);
		if (street.length < 6) {
			valid = false;
			//   console.log($("#street").val().length + " = " + $("#street").val());
			if (!firstrun)
				$("#street").addClass("error");
		}
		if (phone.length < 6) {
			valid = false;
			//   console.log($("#street").val().length + " = " + $("#street").val());
			if (!firstrun)
				$("#phone").addClass("error");
		}
		//  console.log("ZIP: " + zip.length);
		if (zip.length < 4) {
			valid = false;
			if (!firstrun)
				$("#zip").addClass("error");
		}
		//   console.log("town: " + town.length);
		if (town.length < 2) {
			valid = false;
			if (!firstrun)
				$("#town").addClass("error");
		}
		if (valid == true) {
			$("#customer-information .button-next").show();
			$('#customer-information input').removeClass("error");
			//    $('#payment-information .content').show();
			//   $('html, body').animate({scrollTop: $('#payment-information').offset().top}, 200);
			/*$(this).parent().hide();*/
		}
		//else
		//    $("#customer-information .button-next").hide();
		return valid;
	}
	function getCartResult(response) {
		seperator = response.indexOf("||");
		if (seperator > 0) {
			len = response.length;
			seperator += 2;
			//    alert(seperator);
			response = response.substring(seperator, len);
			//console.log(response);
			return response;
		} else return response;
	}
	function getProductsInCart(response) {
		seperator = response.indexOf("||");
		//   alert(seperator);
		productsincart = 0;
		if (seperator > 0) {
			productsincart = response.substring(0, seperator);
			//alert(productsincart);
		}
		return productsincart;
	}
	function isEmail(email) {
		var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		return regex.test(email);
	}
	function updateCartNotification(value) {
		//  console.log("UPDATEID");
		$("#cart-notification").removeClass("pulsate");
		$("#cart-notification").html(value);
		$("#cart-notification").addClass("pulsate");
		setTimeout(function () {
			$("#cart-notification").removeClass('pulsate');
		}, 2000);
	}
	function closeSafetyPackageBadges() {
		$(".close-safety").click(function () {
			$(".add-safety-package").hide();
		});
	}
	$.fn.classes = function (callback) {
		var classes = [];
		$.each(this, function (i, v) {
			var splitClassName = v.className.split(/\s+/);
			for (var j = 0; j < splitClassName.length; j++) {
				var className = splitClassName[j];
				if (-1 === classes.indexOf(className)) {
					classes.push(className);
				}
			}
		});
		if ('function' === typeof callback) {
			for (var i in classes) {
				callback(classes[i]);
			}
		}
		return classes;
	};
	function initMultipleBooking()  {
		if ($(".book-multiple").length > 0)
		{
			$("#confirm-multibooking").click(function(){
				//console.log($('.book-multiple:checkbox:checked'));
				$('.book-multiple:checkbox:checked').each(function () {
					let pid = $(this).attr("id").replace('book-', '')
					console.log(pid); 
					addtoCart(pid)
            		   
        	   
});
			})
			$(".book-multiple").click(function() {
				//console.log($('.book-multiple:checkbox:checked').length);
				if($('.book-multiple:checkbox:checked').length > 0 ) 
				$("#confirm-multibooking").show();
					else
				$("#confirm-multibooking").hide();
			} );
    				
			
		}
		
	}
	function initFilterButtons() {
		 //console.log($("#type_filter").length);
		 
		if ($("#type_filter").length > 0 || $("#brand_filter").length > 0 || $("#size_filter").length > 0) 
		{
			var all = $(".product-row").classes();
		//	console.log(all.length);
						
			$(".filterselect").addClass("remove");
			$(".brandfilterselect").addClass("remove");
			$(".sizefilterselect").addClass("remove");
		//	console.log(all);
			if ($(all).length > 0) 
			{
				var typesfound = brandsfound = sizesfound = 0;
				$(all).each(function (index, value) {
					  //console.log(value);
					 if (value.startsWith("producttype-") && value != "producttype-") 
					{
						$("#filterselect-" + value.replace('producttype-', '')).removeClass("remove");
						$("#filterselect-" + value.replace('producttype-', '')).addClass("available");
						typesfound++;
					}			
					
					if (value.startsWith("size-") && value != "size-") 
					{
						$("#filterselect-" + value.replace('size-', '')).removeClass("remove");
						$("#filterselect-" + value.replace('size-', '')).addClass("available");
						sizesfound++;
					}			
					
					
					if (value.startsWith("productbrand-") && value != "productbrand-"&& value != "productbrand-tyn") 
					{
					//	console.log(value)
						$("#filterselect-" + value.replace('productbrand-', '')).removeClass("remove");
						$("#filterselect-" + value.replace('productbrand-', '')).addClass("available");
						brandsfound++;
					}					
				});
				
				$(".filterselect.remove").remove();
				$(".sizefilterselect.remove").remove();
				$(".brandfilterselect.remove").remove();
				//console.log(brandsfound + " " + typesfound + " " + sizesfound);
			
				if(typesfound > 1)
					$("#type_filter").show();
				else 
					$("#type_filter").hide();
				
				if(sizesfound > 1)
					$("#size_filter").show();
				else 
					$("#size_filter").hide();
				if(brandsfound > 1)
					$("#brand_filter").show();
				else
					$("#brand_filter").hide();
				if ($("#filter-available").length > 0) 
				{
					$("#filter-available").addClass("available");
					
					$("#filter-available").click(function () {
						$(".product-row").removeClass("dont-show-type").show();
						$(".filterselect_icon,.filterselect").removeClass("active");
						$(this).addClass("active");
						$(".enabled-0").toggle();
					});
				}
				if ($("#brandfilter-available").length > 0) 
					{
						$("#brandfilter-available").addClass("available");
						
						$("#brandfilter-available").click(function () {
	
							$(".product-row").removeClass("dont-show-brand").show();
							$(".brandfilterselect_icon,.brandfilterselect").removeClass("active");
							$(this).addClass("active");
							$(".enabled-0").toggle();
						});
					}
					if ($("#sizefilter-available").length > 0) 
					{
						$("#sizefilter-available").addClass("available");
						
						$("#sizefilter-available").click(function () {
	
							$(".product-row").removeClass("dont-show-size").show();
							$(".sizefilterselect_icon,.sizefilterselect").removeClass("active");
							$(this).addClass("active");
							$(".enabled-0").toggle();
						});
					}
	
				if (typesfound > 0) {
					$("#type_filter").show();
					$(".filterselect_icon,.filterselect").click(function () 
					{
						//console.log($(this).hasClass);
						
						if (!$(this).hasClass("active"))
						{
							$("#filter-available, .filterselect_icon,.filterselect").removeClass("active");
							$(".product-row").addClass("dont-show-type");
							var activeid = $(this).attr("id");
							
							setTimeout(function () 
							{
								$(".product-row").hide();
								$(".producttype-" + activeid.replace('filterselect-', '')).show().removeClass("dont-show-type");
							}, 300);
							$(this).addClass("active");
						}
					});
				}
				if (brandsfound > 1) {					
					$(".brandfilterselect").click(function () {
						if (!$(this).hasClass("active"))
							{
							$("#brandfilter-available, .brandfilterselect").removeClass("active");
							$(".product-row").addClass("dont-show-brand");
							var activeid = $(this).attr("id");
							//console.log(activeid);
							setTimeout(function () {
								$(".product-row").hide();
								$(".productbrand-" + activeid.replace('filterselect-', ''))
								$(".productbrand-" + activeid.replace('filterselect-', '')).show().removeClass("dont-show-brand");
							}, 300);
							$(this).addClass("active");
						}
					});
				}
				if (sizesfound > 1) {					
					$(".sizefilterselect").click(function () {
							if (!$(this).hasClass("active"))
							{
							$("#sizefilter-available, .sizefilterselect").removeClass("active");
							$(".product-row").addClass("dont-show-size");
							var activeid = $(this).attr("id");
							//console.log(activeid);
							setTimeout(function () {
								$(".product-row").hide();
								$(".size-" + activeid.replace('filterselect-', ''))
								$(".size-" + activeid.replace('filterselect-', '')).show().removeClass("dont-show-size");
							}, 300);
							$(this).addClass("active");
						}
					});
				}
			}
			//alert("REMOVE IT");
		}
	}
	function initSellFormRequests(submiturl)  {
		//alert('init SFR')
		$("#form-sell-request").on("submit", function(event){
			event.preventDefault();
			var formValues= $(this).serialize();
		//	console.log(submiturl)
		//	console.log(formValues);
			firstname = $("#firstname")[0].value;
			lastname = $("#lastname")[0].value;
			if (firstname.length > 2) 
			{
				$("#firstname").removeClass("error");
				if (lastname.length > 2) {
					$("#lastname").removeClass("error");
					if (isEmail($("#email").val())) {
						$.post(submiturl, formValues, function(data){
							// Display the returned data in browser
							$("#additional-products .content").html(data);
						});
					} else
						$("#email").addClass("error");
				}
				else
					$("#lastname").addClass("error");
			}
			else  	
				$("#firstname").addClass("error");
		});
	}
	function addtoCart(pid, for_pid = 0, pgid= 0, which = ".button-addtocart")
	{
		var obj_toworkwith = $("#product-row-addtocart-"+pid);
		
	//	console.log(obj_toworkwith.attr("id"));
		if(for_pid == 0)
			 for_pid = obj_toworkwith.attr("for_pid");
		
		if(pgid == 0)
			pgid = obj_toworkwith.attr("data-productgroup");
		
			if (pgid == "0")
				pgid = "";
			
			//alert(pid + " " + for_pid + " " + pgid) ;
				
			//console.log(obj_toworkwith);
			Cookies.set("nocache", 1, {expires: 1});
			
			$.ajax({
				url: base_url + "/cart/add",
				curobj: obj_toworkwith,
				for_pid: for_pid,
				pid: pid,
				pgid: pgid,
				method: "POST", //First change type to method here
				data: {
					product_id: pid,
					for_product_id: for_pid,
				},
				success: function (response) {
				//	console.log(obj_toworkwith);
					//console.log(obj_toworkwith.curobj);
					//alert("SUCCESS");
					
					$(obj_toworkwith).parent(".product-row-cartaction").find(".in-cart").toggleClass("hidden");
					$(obj_toworkwith).toggle();
					productsincart = getProductsInCart(response);
					response = getCartResult(response);
					$("#cart-content").html(response);
			
					if (pgid.length >= 1 && which != ".add-additional-product") {
						
						
						//console.log("2");
					//	console.log(obj_toworkwith);
						Cookies.set("nocache", 1, {expires: 1});
						 //console.log("Sent request " + obj_toworkwith.for_pid + " " +  obj_toworkwith.pgid);
						 //console.log("Sent request 2 " + for_pid + " " +  pgid + " " +  pid);
						$.ajax({
							url: base_url + "/products/additional",
							method: "POST", //First change type to method here
							data: {
								for_product_id: pid,
								productgroup: pgid
							},
							success: function (response) {
								//alert("DONE");
								//     console.log(response.length);
								if (response.length > 0) {
									startAdditionalOverlay(response);
								}
								initProductButtons(".add-additional-product");
								//    console.log(response);
							},
							error: function (response) {
								alert("error " + response);
							}
						});
						// console.log("ENd Sent request");
					}
					//  initProductButtons();
					initCartButtons();
					updateCartNotification(productsincart);
					//       console.log("end success");
				},
				error: function () {
					//  alert("error");
				}
			});
	}
	function initProductButtons(which) {
		if (typeof which == 'undefined')
			which = ".button-addtocart";
		// console.log("HICH IS" + which);
		if($("#save-body-data").length > 0 )
		{
			$("#save-body-data").click(function () {
				var for_pid = $(this).attr("for_pid");
				var weight =  $("#cyclist_weight").val();
				var height =  $("#cyclist_height").val();
				var stride_length =  $("#cyclist_stride_length").val();
			//	alert(weight + " " + height);
				$.ajax({
					url: base_url + "/cart/add/data",
					method: "POST", //First change type to method here
					data: {
						for_product_id: for_pid,
						cyclist_height: height,
						cyclist_weight: weight,
						cyclist_stride_length: stride_length,
					},
					success: function (response) {
						$("#data-input-actions").html(response);
					}					,
					error: function () {
						  alert("error");
					}
				});
			});
		}
		$(which).click(function () {
			var pid = $(this).attr("pid");
			
			var for_pid = $(this).attr("for_pid");
			var pgid = $(this).attr("data-productgroup");
			if (pgid == "0")
				pgid = "";
			addtoCart(pid, for_pid, pgid, which);
		
		
		});
		
		if ($(".edit-price").length > 0) {
			$(".edit-price").click(function(){
				var price_row = $(this).parent().parent();
				price_row.find(".price-output").toggle();
				price_row.find(".edit-price-form").toggle();
			});
		}
		if ($(".sell-badge").length > 0) {
			//    console.log("Found Changebike);
			$(".sell-badge").click(function () {
				var for_pid = $(this).attr("for_pid");
				var processurl = base_url + "/bi/getsellinfo/" + for_pid+"/process";
				$.ajax({
					type: "GET",
					dataType: ' text',
					url: base_url + "/bi/getsellinfo/" + for_pid,
					success: function (response) {
						startAdditionalOverlay(response);
						initSellFormRequests(processurl);
					},
					error: function () {
					}
				});
			});
		}
		$(".button-removefromcart").click(function () {
			//   console.log("REMOVE");
			var pid = $(this).attr("pid");
			var for_pid = $(this).attr("for_pid");
			//  console.log("remove2 " + pid + " fp:" + for_pid);
			//    alert("SUCCESS");
			var buttonclicked = this;
			$.ajax({
				url: base_url + "/cart/remove",
				method: "POST", //First change type to method here
				data: {
					product_id: pid, // Second add quotes on the value.
					for_product_id: for_pid, // Second add quotes on the value.
				},
				success: function (response) {
					//     console.log("SUCCESS " + response);
					//      alert("SCUCESS");
					if ($(buttonclicked).hasClass("button-checkout")) {
						self.location.href = base_url + "/checkout";
						return false;
					} else {
						productsincart = getProductsInCart(response);
						response = getCartResult(response);
						$("#cart-content").html(response);
						initCartButtons();
						updateCartNotification(productsincart);
					}
				},
				error: function () {
					//   alert("error");
					self.location.href = base_url + "/checkout";
					return false;
				}
			});
		});
	}
	function checkAgreements() {
		var agb = document.getElementById("agree-agb");
		var dsgvo = document.getElementById("agree-dsgvo");
		var rent = document.getElementById("agree-rent");
		var external = document.getElementById("agree-externalagreement");
		//   alert($("#additionalinfos").val().length);
		// Get the output text
		var text = document.getElementById("pay-now-container");
		var options = document.getElementsByName('paymentoption');
		var selectedoption = "";
		for (var i = 0; i < options.length; i++) {
			if (options[i].checked) {
				selectedoption = options[i].value;
			}
		}
		//   console.log("checking SO:" + selectedoption + " " + agb.checked + " " + dsgvo.checked + " " + rent.checked);
		// If the checkbox is checked, display the output text
		if (($("#agree-externalagreement").length <= 0 || ($("#agree-externalagreement").length > 0 && external.checked == true)) && agb.checked == true && dsgvo.checked == true && rent.checked == true && selectedoption != "") {
			$("#pay-now-container").removeClass("hideit");
			$("#data-missing").addClass("hideit");
			return true; // = valid
			// text.style.display = "block";
		} else {
			//text.style.display = "none";
			$("#data-missing").removeClass("hideit");
			$("#pay-now-container").addClass("hideit");
			return false; // = not valid
		}
	}
	function validateCheckout() {
		valid = false;
		valid = validateCustomerInfo(false);
		valid = checkAgreements();
		var external = document.getElementById("agree-externalagreement");
		if ($("#additionalinfos").val().length < 5 && external.checked == true) {
			valid = false;
			$("#additionalinfos").addClass("error");
		}
		//valid = true; // debuggin
		if (valid == true) {
		}
		return valid;
	}
	var cart;
	$(document.body).on('touchmove', onScroll); // for mobile
	$(window).on('scroll', onScroll);
// callback
	function onScroll() {
		//if (window.matchMedia('(min-width: 1025px)').matches) #
		{
			if ($(document).scrollTop() >= 50) {
				// user scrolled 50 pixels or more;
				// do stuff
				$("body").addClass("scrolled");
			} else {
				$("body").removeClass("scrolled");
			}
		}
		if ($(window).scrollTop() + window.innerHeight >= document.body.scrollHeight) {
		}
	}
	function validateEmail(email) {
		const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		return re.test(String(email).toLowerCase());
	}
	$(document).scroll(function () {
	});
	function hideNLPopup() {
		// alert("HIDE IT");
		Cookies.set("nlshown", 1, {expires: 4});
	}
	$(window).load(function () {
		var newsletter_shown = Cookies.get("nlshown");
		var newsletter_registered = Cookies.get("nlreged");
		if (typeof newsletter_shown == 'undefined')
			newsletter_shown = 0;
		if (typeof newsletter_registered == 'undefined')
			newsletter_registered = 0;
		$("#sib-form-submit").on("click", function () {
			//    alert("SUBTM MIT");
			if (validateEmail($("#EMAIL").val()) && $('#OPT_IN').is(':checked')) {
				$("#sib-form").submit();
				hideNLPopup();
				Cookies.set("nlreged", 1, {expires: 365});
			}
		});
		newsletter_shown = 1; // END
		if (!window.location.pathname.endsWith("newsletter-gewinnspiel") && newsletter_shown <= 0 && newsletter_registered <= 0) {
			newsletter_shown++;
			$("#close-popup").click(function () {
				$("#newsletter-popup").hide();
				hideNLPopup();
			});
			setTimeout(function () {
				//  $("#cart-notification").removeClass('pulsate');
				$("#newsletter-popup").show();
				//    hideNLPopup();
				hideNLPopup();
			}, 10000);
		}
		if ($(".testimonials").length > 0) {
			var testimonials_carousel = $('.testimonials');
			testimonials_carousel.owlCarousel({
				items:4,
				loop:true,
				margin:20,
				autoplay:true,
				autoplayTimeout:3000,
				autoplayHoverPause:true
			});
		}
		if ($(".banner").length > 0) {
			  console.log("INIT CAROUSEL ");
			const $owlCarousel = $('.banner').owlCarousel({
					items: 1,
					margin: 0,
					autoplay: true,
					autoPlay: 5000,
					nav: false,
					dots: true,
					singleItem: true,
					autoplayTimeout: 5000,
					loop: true,
					stagePadding: 0,
					onChanged: function (e) {
						//  console.log("onchanged")
						$(".owl-slide-animated, .enjoy, .your-ride,.banner-slogan").removeClass("is-transitioned");
						const $currentOwlItem = $(".owl-item").eq(e.item.index);
						setTimeout(function () {
								$currentOwlItem.find(".owl-slide-animated").addClass("is-transitioned");
								 $("section").show();
							},
							5000);
						setTimeout(function () {
								$currentOwlItem.find(".banner-slogan").addClass("is-transitioned");
								$("section").show();
							},
							1000);
						setTimeout(function () {
								$currentOwlItem.find(".enjoy").addClass("is-transitioned");
								$("section").show();
							},
							3000
						)
						;
						setTimeout(function () {
								$currentOwlItem.find(".your-ride").addClass("is-transitioned");
								$("section").show();
							},
							2100
						)
						;
					},
					onInitialized: function () {
						//  console.log("ON INIT CAROU");
						setTimeout(function () {
								$(".owl-item.active .owl-slide-animated").addClass("is-transitioned");
								 $("section").show();
							},
							3000
						)
						;
						setTimeout(function () {
								$(".owl-item.active .enjoy").addClass("is-transitioned");
								$("section").show();
							},
							1500
						)
						;
						setTimeout(function () {
								$(".owl-item.active .your-ride").addClass("is-transitioned");
								$("section").show();
							},
							2100
						)
						;
					}
				})
			;
			
						console.log($owlCarousel);
						console.log($(".owl-carousel"));
						$(".owl-carousel").on("initialized.owl.carousel", () => {
							console.log("ON INIT CAROU");
							setTimeout(() => {
								$(".owl-item.active .owl-slide-animated").addClass("is-transitioned");
								$("section").show();
								// console.log("SHOW TRANS");
							}, 3000);
							setTimeout(() => {
								$(".owl-item.active .enjoy").addClass("is-transitioned");
								$("section").show();
							}, 1500);
							setTimeout(() => {
								$(".owl-item.active .your-ride").addClass("is-transitioned");
								$("section").show();
							}, 2100);
						});
			$owlCarousel.on("changed.owl.carousel", e => {
				console.log("ON CHANGE CAROU");
				$(".owl-slide-animated, .enjoy, .your-ride").removeClass("is-transitioned");
				const $currentOwlItem = $(".owl-item").eq(e.item.index);
				$currentOwlItem.find(".owl-slide-animated").addClass("is-transitioned");
				$currentOwlItem.find(".enjoy").addClass("is-transitioned");
				$currentOwlItem.find(".your-ride").addClass("is-transitioned");
			});
  
		}
		$("#splashscreen").hide();
	});
	function initChangeTimeProcessing() {
		if ($("#process-change-time").length > 0) {
			$("#process-change-time").click(function () {
				var changeurl = $(this).attr('data-url');
				//console.log("ULR " + changeurl);
			//	alert($("#datefrom").val());
				if (changeurl.length > 0) {
					datefrom =$("#datefrom").val();
					dateuntil =$("#dateuntil").val();
					if(datefrom.length <=  0)
					{
						datefrom =$("#datefrom-input").val();
						dateuntil =$("#dateuntil-input").val();
					}
				/*	console.log(datefrom);
					console.log(dateuntil);
					var date1 = new Date(datefrom);
					var date2 = new Date(dateuntil);
					console.log(date1);
					console.log(date2);
				//	if(date1 < date2)
					alert();
					exit();*/
					$.ajax({
						url: changeurl,
						method: "POST", //First change type to method here
						data: {
							type : "process",
							from: datefrom,
							until: dateuntil, // Second add quotes on the value.
						},
					success: function (response) {
							$("#additional-products .content").html(response);
							$("#additional-overlay-container").show();
							$("#additional-products .close-additional").click(function () {
								$("#additional-overlay-container").hide();
							});
							return false;
						},
						error: function () {
						}
					});
					//else
					//	alert("Bitte gültige Zeiten eingeben.");
				}
			});
		}
	}
	function startAdditionalOverlay(content)
	{
		$("#additional-products .content").html(content);
		$("#additional-overlay-container").show();
		$("#additional-products .close-additional").click(function () {
			$("#additional-overlay-container").hide();
		});
	}
	function showProgress() {
		//  $('.progress-bar').width('83%');
		//  $('.node__5').addClass('node--active').prevAll('.node').addClass('node--complete');
	}
	$(document).ready(function () {
		if($(".product-row").length > 0)
		{
			document.querySelectorAll(".product-row").forEach(row => {
		//console.log("ADD TO ROW"); 	
        	row.addEventListener("click", function () {
            	let url = this.getAttribute("data-url");
            	redirectWithCoordinates(url);
    	    });
		    });
		}
		
		$('#filter-overlay').appendTo('#page');
		$('#filter-sidebar').appendTo('#page');
		initFilterButtons();
		initMultipleBooking();
		if($("#model-container").length > 0)
		{
			$('[data-quantity="plus"]').click(function (e) {
				// Stop acting like a button
				e.preventDefault();
				// Get the field name
				fieldName = $(this).attr('data-field');
				idtosent = $('input[name=' + fieldName + ']').attr('data-pid');
				//	console.log(idtosent);
				// Get its current value
				var currentVal = parseInt($('input[name=' + fieldName + ']').val());
				// If is not undefined
				if (!isNaN(currentVal)) {
					// Increment
					currentVal++;
					$('input[name=' + fieldName + ']').val(currentVal);
				} else {
					// Otherwise put a 0 there
					currentVal = 0;
					$('input[name=' + fieldName + ']').val(0);
				}
			});
			$('[data-quantity="minus"]').click(function (e) {
				// Stop acting like a button
				e.preventDefault();
				// Get the field name
				fieldName = $(this).attr('data-field');
				idtosent = $('input[name=' + fieldName + ']').attr('data-pid');
				// Get its current value
				var currentVal = parseInt($('input[name=' + fieldName + ']').val());
				// If it isn't undefined or its greater than 0
				if (!isNaN(currentVal) && currentVal > 0) {
					// Decrement one
					currentVal--;
					$('input[name=' + fieldName + ']').val(currentVal);
				} else {
					// Otherwise put a 0 there
					$('input[name=' + fieldName + ']').val(0);
					currentVal = 0;
				}
			});
		}
		$("#form_search_bikes_submit").click(function(){
			$("#product-container-results .search-results,.form_search_bikes_submit-container").hide("slow");
			$("#product-container-results #loading-search-results").show();
			catid = $(".category-container").attr("data-cat-id");
			datefrom =$("#f_from").val().replace(/\s/g, '+');
			dateuntil =$("#f_until").val().replace(/\s/g, '+');
			if(catid > 0)
			{
			$.ajax({
				type: "GET",
				dataType:' text',
				url: base_url + "/bi/bikes/search/"+ catid + "/"+datefrom+"/"+dateuntil+"/list",
			//	data: 'name=' + $(this).val(),
				beforeSend: function() {
				},
				success: function(data) {
					//alert(data);
					$("#product-container-results .search-results").html(data);
					$("#product-container-results #loading-search-results").hide();
					$("#product-container-results .search-results, .form_search_bikes_submit-container").show("slow");
					//initSellFormRequests();
					initProductButtons();
					initFilterButtons();
					initMultipleBooking();
				},
				error: function(xhr, status, error) {
					//$("#product-container-results .search-results").html(xhr.responseText);
					//alert(xhr.responseText);
				//	var err = eval("(" + xhr.responseText + ")");
				//	alert(err.Message);
				}
			});}
			else console.log("no catid for searching");
		//	alert("Search for it");
			return false;
		});
			$("#form_search_bikes_submit").trigger("click");
			
			if ($('.print-page').length > 0) {
				$('.print-page').click(function () {
					window.print();
				});
			}
			if (window.location.href.indexOf("mieten/") > -1) { // etc
				Cookies.set("nocache", 1, {expires: 1});
			}
			if ($('.iframe-btn').length > 0)
				$('.iframe-btn').fancybox({
					'width': 900,
					'height': 600,
					'type': 'iframe',
					'autoScale': false
				});
			$(".admin-submenu-headline").click(function(){
				$(this).siblings(".admin-submenu").toggle();
			});
			if ($("#partner-footer .partner").length > 0 && typeof $('#partner-footer').owlCarousel !== "undefined") {
				//   console.log("init pf");
				$('#partner-footer').owlCarousel({
					loop: true,
					margin: 40,
					nav: true,
					autoplay: true,
					autoplayTimeout: 3000,
					autoplayHoverPause: true,
					responsive: {
						0: {
							items: 2
						},
						600: {
							items: 4
						},
						1000: {
							items: 6
						},
						1400: {
							items: 8
						}
					}
				});
			}
			
				if ($(".button-search-products").length > 0 )
				{
					$(".button-search-products").click(function () {
						if($(".search-zip-overall").val().length > 0)
						{
							var zipfield = $(this).parent().find(".search-zip-overall");
							var zip = zipfield.val();
								if(zip.length > 3)
								{
									zipfield.removeClass("field-error");
									zipfield.parent().find(".zip-field-error").remove();
									$(bike_action_result).hide();
									$(loadingcontainer).show();
									$.ajax({
									url: base_url + "/bi/search/categoryproducts",
									method: "POST", //First change type to method here
									data: {
										category: product,
										zip : zip,
									},
									success: function (response) {
										//alert(response);
										$(loadingcontainer).hide();
										//$(this).closest(".loading-search-results, .bike-action-result")
										$(bike_action_result).show();
										$(bike_action_result).html(response);
										$('html, body').animate({scrollTop: $(bike_action_result).offset().top - 150}, 300);
										//initTimeSelection();
									},
									error: function () {
										//  alert("error");
									}
								});}
								else {
									zipfield.addClass("field-error");
									zipfield.after("Bitte eine gültige Postleitzahl eingeben.
")
								}
								
								alert( $(".search-zip-overall").val().length);
								$(".search-results").html();
						}
					});
				}
			if ($(".button-search-teststation").length > 0)
			{
				$(".button-search-teststation").click(function () {
					//console.log($(this).parent().parent().parent().parent());
				    var loadingcontainer = 	$(this).parent().parent().parent().find(".loading-search-results");
					var bike_action_result = 	$(this).parent().parent().parent().find(".bike-action-result");
					//$(this).closest(".loading-search-results, .bike-action-result").toggle();
					var product = $(this).attr("data-product");
					var zipfield = $(this).parent().find(".search-zip");
				//	console.log(zipfield)
					var zip = zipfield.val();
				//	console.log(zip);
				//	alert(zip.length);
					if(zip.length > 3)
					{
						zipfield.removeClass("field-error");
						zipfield.parent().find(".zip-field-error").remove();
						$(bike_action_result).hide();
						$(loadingcontainer).show();
						$.ajax({
						url: base_url + "/bi/search/teststations",
						method: "POST", //First change type to method here
						data: {
							product: product,
							zip : zip,
						},
						success: function (response) {
							//alert(response);
							$(loadingcontainer).hide();
							//$(this).closest(".loading-search-results, .bike-action-result")
							$(bike_action_result).show();
							$(bike_action_result).html(response);
							$('html, body').animate({scrollTop: $(bike_action_result).offset().top - 150}, 300);
							//initTimeSelection();
						},
						error: function () {
							//  alert("error");
						}
					});}
					else {
						zipfield.addClass("field-error");
						zipfield.after("Bitte eine gültige Postleitzahl eingeben.
")
					}
				});
		}
			if ($("#booking-container-bikes").length > 0)
				initTimeSelection();
			$("#sib-form-submit").on("click", function () {
			});
			if($("#bikestatus").length > 0)
				$("#loading-search-results").hide();
						$("#map-activator").on("click", function () {
				$("#map, #map-activator .on, #map-activator .off").toggle();
			});
			$(".mobile-category-info-icon").click(function () {
				$(this).find("span").toggle();
				$(".mobile-category-info, .category-info").toggle();
			});
			$(".notification-badge").click(function () {
				$(".notification-badge > div").toggle();
				$(".notification-overlay").toggle();
			});
			$("#main-menu-switch").click(function () {
				$("#cart").hide();
				$("#navigation_main").toggleClass("is-active");
				$("#navigation_main_user").toggleClass("is-active");
				$("#main-menu-switch").toggleClass("is-active");
			});
			$("#main-admin-switch").click(function () {
				$("#cart").hide();
				$("#admin-navi").toggleClass("is-active");
				$("#main-admin-switch").toggleClass("is-active");
			});
			$("#delcoupon").click(function () {
				//  console.log("delco");
				$.ajax({
					url: base_url + "/cart/remove",
					method: "POST",
					data: {
						product_id: "coupons", // Second add quotes on the value.
					},
					success: function (response) {
						//$("#fullcart-content").html(response);
						location.reload();
					},
					error: function () {
						//  alert("error");
						location.reload();
					}
				});
			});
			
			function checkPriceToPay() {
				if ($("#paymentoption_free").length > 0) {
				//	alert("CHECK PTP");
					pricetopay = parseFloat($("#fullcart-content #pricetopay").text().replace(',', '.'));
					  //console.log(pricetopay);
			//		alert(pricetopay);
					if (pricetopay == 0) {
						//console.log("show it");
						setTimeout(function () {
							$("#paymentoption_free_container").removeClass("hide");
							$("#paymentoption_free").prop('checked', true);
						}, 1000);
						setTimeout(function () {
							       $(".paymentoption_money").addClass("hide");
						}, 1000);
						// setTimeout(
					} else {
						setTimeout(function () {
							$(".paymentoption_money").removeClass("hide");
						}, 1000);
						setTimeout(function () {
							$("#paymentoption_free_container").addClass("hide");
						}, 1000);
					}
				}
				//  else console.log("Free not found");
			}
			$("#checkcoupon").click(function () {
				// console.log($("#coupon").val());
				if ($("#coupon").val().length > 3) {
					// self.location.href="/checkout/coupon/" + $("#coupon").val();
					Cookies.set("nocache", 1, {expires: 1});
					$.ajax({
						url: base_url + "/cart/add",
						method: "POST", //First change type to method here
						data: {
							coupon: $("#coupon").val(),
							product_id: -10, // Second add quotes on the value.
						},
						success: function (response) {
							$("#fullcart-content").html(response);
							//    if($().val() == 0)
							//   location.reload();
						},
						error: function () {
							//  alert("error");
							//   location.reload();
						}
					});
				}
				setTimeout(function () {
					checkPriceToPay();
				}, 2000);
				//checkPriceToPay();
				// alert();
			});
			checkPriceToPay();
			$("#splashscreen").on("click", function () {
				$(this).hide();
			});
			setTimeout(function () {
				$('#splashscreen').hide();
			}, 6000);
			$(".booking-container > .container-head,.collapsible-container > .container-head").on("click", function () {
				$(this).toggleClass("collapsed");
				$(this).parent().find(".collapsible").toggleClass("hidden");
				$(this).parent().find(".fa").toggleClass("hidden");
			});
			if ($(".expanding-box-header").length > 0)
				$(".expanding-box-header").on("click", function () {
					//console.log("click");
					$(this).parent().find(".expanding-box-text").toggleClass("expanded");
					$(this).find(".expanding-icons").find(".minus").toggle();
					$(this).find(".expanding-icons").find(".plus").toggle();
					var boxoffset = $(this).offset().top + 200;
					$('html,body').animate({scrollTop: boxoffset}, 700, 'swing');
				});
			/*
			OLD BANNER
			*/
			/*
			setTimeout(function () {
				  $(".overlay.animate").animate({
					  opacity: 1
				  }, {duration: 700});
				  setTimeout(function () {
					  $(".booking-button").animate({
						  opacity: 1
					  }, {duration: 700});
				  }, 2500);
			}, 2500);
	  */
//        $('#bike_search_from').datetimepicker('setStartDate', "'" + currentdate.getFullYear() + ":" + currentdate.getMonth() + ":" + currentdate.getDay() + ":" + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds());
			$("#payment-information input").change(function () {
				//    alert("HCNAGE");
				checkPriceToPay();
				$("#button-paymentoptions-next").show();
			});
			if ($("#customer-information .button-next").length > 0) {
				validateCustomerInfo(true);
				checkPriceToPay();
			}
			$(".checkout-agreement input, .paymentoption").click(function () {
				checkAgreements();
			});
			$('.checkout').on('submit', function (e) {
				// console.log("submit it");
				//console.log($("#confirm-information .container-content").is(':visible'));
				if ($("#confirm-information .container-content").css('display', 'none') == true) {
					e.preventDefault();
					//  console.log("no submit");
				} else {
					//e.preventDefault();
					// console.log("do submit");
					// this.submit();
				}
				//     if(!$("").is(":visble"))
				/*  var len = $('#username').val().length;
				  if (len < 6 && len > 1) {
					  this.submit();
				  }*/
			});
			$("#pay-now").click(function () {
				if (validateCheckout() == true) {
					//alert("now");
					//return false;
					return true;
				} else {
					return false;
				}
			});
			$("#customer-information .button-next").click(function () {
				if (validateCustomerInfo(false) == true) {
					$('#payment-information .content').show();
					$('html, body').animate({scrollTop: $('#payment-information').offset().top}, 200);
				}
				//validateCheckAgreements();
			});
			$(document).on('focus', '#email', function () {
				$(this).addClass('input2').removeClass('input1');
			});
			if ($('#customer-information .content').length > 0) {
				$('input:radio[name="paymentoption"]').change(
					function () {
						console.log($(this).val());
						if ($(this).is(':checked') && $(this).val() == 'genusscard') {
							$("#genusscardno").show();
						} else $("#genusscardno").hide();
					});
				$('#customer-information input').focus(function () {
					$(this).removeClass("error");
				});
				$(document).on('blur', '#email', function () {
					//   validateCustomerInfo(false);
					//console.log("CHECK USERNAME");
					if (isEmail($("#email").val())) {
						check_username($("#email").val());
						$("#email").removeClass("error");
					} else
						$("#email").addClass("error");
					//$(this).addClass('input1').removeClass('input2');
				});
				$(document).on('blur', '#town', function () {
					validateCustomerInfo(false);
				});
				/*     $('#customer-information .content').show();
					 $("#email").on('blur', function () {
						 check_username($(this).val());
					 });*/
				// $('#customer-information .content').hide();
			}
			initProductButtons();
			//initSellFormRequests();
			$("#button-cart-empty").click(function () {
				$.ajax({
					url: base_url + "/cart/remove",
					method: "POST",
					data: {product_id: "all",},
					success: function (response) {
						$("#cart-content").html(response);
					}
				});
			});
			if ($(".viewselect_icon").length > 0) {
				//  console.log("ICONS found");
				$("#viewselect_list").on("click", function () {
					$(".viewselect_icon").removeClass("active");
					$(this).addClass("active");
					$(".booking-container").removeClass("view-grid");
					$(".booking-container").addClass("view-list");
				});
				$("#viewselect_grid").on("click", function () {
					$(".viewselect_icon").removeClass("active");
					$(".booking-container").addClass("view-grid");
					$(".booking-container").removeClass("view-list");
				});
			}
			$(".cart-icon").click(function () {
				$("#login-form").hide();
				$("#cart").toggle();
			});
			$("#showlogin").click(function () {
				$("#cart").hide();
				$("#login-form").toggle();
				return false;
			});
			if ($('#flash-message').length > 0) {
				//   $("#flash-message").addClass("pulsate");
				$('#flash-message').click(function () {
					$(this).hide();
				});
				setTimeout(function () {
					$('#flash-message').hide();
				}, 10000);
			}
		}
	);
	document.addEventListener('DOMContentLoaded', function () {
    // Ein-/Ausklappen der Filtergruppen
    document.querySelectorAll('.filter-group-title').forEach(title => {
        title.addEventListener('click', function () {
            const options = this.nextElementSibling;
            options.classList.toggle('visible');
        });
    });
    // Sidebar ein-/ausblenden
    const filterSidebar = document.getElementById('filter-sidebar');
    const filterOverlay = document.getElementById('filter-overlay');
    $("#filter-toggle-btn, .close-filter").click(toggleFilterSidebar);
    function toggleFilterSidebar() {
        filterSidebar.classList.toggle('active');
        filterOverlay.style.display = filterSidebar.classList.contains('active') ? 'block' : 'none';
    }
	// Funktion zum Anwenden der Filter und Seite neu laden
	if($("#apply-filters").length > 0)
	{
document.getElementById('apply-filters').addEventListener('click', function () {
    const filters = {};
    let seatHeightModified = false; // Flag für Sitzhöhe-Änderung
    // Eingabefelder durchgehen und Werte sammeln
    document.querySelectorAll('input[name]').forEach(input => {
        const filterName = input.name;
        if ((input.type === 'checkbox' && input.checked) || input.type === 'range') {
            if (input.type === 'checkbox') {
                // Checkboxen sammeln und als kommaseparierte Liste speichern
                if (!filters[filterName]) {
                    filters[filterName] = [];
                }
                filters[filterName].push(input.value);
            } else if (input.type === 'range') {
                // Dynamische Standardwerte für Ranges holen
                const defaultMin = input.getAttribute('min');
                const defaultMax = input.getAttribute('max');
                // Prüfen, ob sich einer der Werte von den Standardwerten unterscheidet
                if ((filterName.includes('min') && input.value != defaultMin) || 
                    (filterName.includes('max') && input.value != defaultMax)) {
                    seatHeightModified = true;
                }
            }
        }
    });
    // Wenn eine Änderung bei Sitzhöhe festgestellt wurde, beide Werte in die Filter aufnehmen
    if (seatHeightModified) {
        const minInput = document.querySelector('input[name="seat_height_min"]');
        const maxInput = document.querySelector('input[name="seat_height_max"]');
        if (minInput) filters['seat_height_min'] = minInput.value;
        if (maxInput) filters['seat_height_max'] = maxInput.value;
    }
    // Überprüfen, ob ein Standort gesetzt ist (aus sessionStorage)
    const savedLat = sessionStorage.getItem("latitude");
    const savedLon = sessionStorage.getItem("longitude");
    if (savedLat && savedLon) {
        filters['latitude'] = savedLat;
        filters['longitude'] = savedLon;
    }
    // Query-String generieren
    const queryParams = new URLSearchParams();
    for (const key in filters) {
        if (Array.isArray(filters[key])) {
            queryParams.append(key, filters[key].join(',')); // Mehrfachwerte als kommaseparierte Liste
        } else {
            queryParams.append(key, filters[key]);
        }
    }
    // Seite mit neuen Parametern laden
    window.location.search = queryParams.toString();
});
}
    // Funktion zum Setzen der Filterwerte aus dem Query
    function setFiltersFromQuery() {
        const params = new URLSearchParams(window.location.search);
        // Checkboxen und Range-Inputs anhand der Query-Parameter setzen
        document.querySelectorAll('input[name]').forEach(input => {
            const filterName = input.name;
            if (params.has(filterName)) {
                const queryValue = params.get(filterName);
                if (input.type === 'checkbox') {
                    // Checkboxen aktivieren, wenn der Wert vorhanden ist
                    const values = queryValue.split(',');
                    if (values.includes(input.value)) {
                        input.checked = true;
                    }
                } else if (input.type === 'range') 
				{
                    // Range-Werte setzen
                    input.value = queryValue;
                    updateSeatHeightValue(filterName.includes('min') ? 'min' : 'max', input.value);
                }
            }
        });
    }
    // Sitzhöhe-Werte aktualisieren
    window.updateSeatHeightValue = function (type, value) {
        document.getElementById(`seat_height_${type}-value`).textContent = value;
    };
    // Filterwerte nach dem Laden der Seite setzen
    setFiltersFromQuery();
});
}());