jQuery(document).ready(function($){

	jQuery('.page-id-1214 #billing_phone_field').append('<span class="phone_info">Bitte geben Sie ein gültiges Mobilnummer an, um Informationen zum Status Ihrer Bestellung per SMS zu erhalten.</p>');
	jQuery('.page-id-1402 #billing_phone_field').append('<span class="phone_info">Forneça um número de celular válido para receber informações sobre o status do seu pedido via SMS.</p>');

	jQuery('.page-id-15 #billing_phone_field').append('<span class="phone_info">Receive information about the status of your order via SMS.</p>');



	jQuery('.page-id-1398 #billing_phone_field').append('<span class="phone_info">Geef een geldig mobiel nummer op om via sms informatie over de status van uw bestelling te ontvangen.</p>');
	jQuery('.page-id-1406 #billing_phone_field').append('<span class="phone_info">Geef een geldig mobiel nummer op om via sms informatie over de status van uw bestelling te ontvangen.</p>');


	jQuery('.page-id-1400 #billing_phone_field').append("<span class='phone_info'>Veuillez fournir un numéro de mobile valide pour recevoir des informations sur l'état de votre commande par SMS.</p>");

	jQuery('.page-id-1404 #billing_phone_field').append("<span class='phone_info'>Veuillez fournir un numéro de mobile valide pour recevoir des informations sur l'état de votre commande par SMS.</p>");



	jQuery(".product-block, .new_checkout__product, .product__item").click(function(){
		jQuery(".product-block, .new_checkout__product, .product__item").removeClass('is-selected');
		jQuery(this).addClass("is-selected");

		jQuery(".product-block.is-selected, .new_checkout__product.is-selected").find(".product-link a").text(siteData.chosen_text);
		jQuery(".product-block:not(.is-selected), .new_checkout__product:not(.is-selected)").find(".product-link a").text(siteData.choose_text);

		var cvalue=jQuery(this).attr("data-prdid");
		jQuery.ajax({
				type: "POST",
				dataType: "json",
				url: siteData.site_url+'/wp-admin/admin-ajax.php',
				data: {
					action: "update_checkout",
					cvalue: cvalue
				},
				success: function(response) {

					//jQuery('.pack').removeClass('is-selected');
					//jQuery('.pack_'+response.new_product).addClass('is-selected');
					//jQuery('.loaderc').hide();

					//if (jQuery(window).width() < 881) {
					//	jQuery('html, body').animate({
					//		scrollTop: jQuery("#pay").offset().top - 100
					//	}, 1000);
					//}


				}
			});

        if (jQuery(event.target).hasClass('to_reviews_txt')) {
            const el = document.querySelector(".checkout-reviews-main-wrapper");
            const y = el.getBoundingClientRect().top + window.pageYOffset + -200;

            window.scrollTo({top: y, behavior: 'smooth'});

            return;
        }

        document.querySelector("#wfacp_checkout_form").scrollIntoView({ block: "start", behavior: "smooth" });
  });


	jQuery('.review_star_li').hover(
                function() {
					 jQuery(this).prevAll().addClass('star-hovered');
                       jQuery(this).addClass('star-hovered');

					  // var dataprtext=jQuery(this).attr('data-prtext');
					  // jQuery("#reviewrateText").text(dataprtext);
					 jQuery(this).nextAll().removeClass('star-hovered');
                },
                function() {
                   jQuery(this).prevAll().removeClass('star-hovered');
                       jQuery(this).removeClass('star-hovered');
					 jQuery(this).nextAll().removeClass('star-hovered');
					  /*var dataprtext=jQuery(".review_star_li.active:last").attr('data-prtext');
					  if(dataprtext!= null && dataprtext !=""){
						jQuery("#reviewrateText").text(dataprtext);
					   }else{
					   jQuery("#reviewrateText").text("");
					   }*/
                }
            );
		jQuery('.review_star_li').on('click',function() {
			   jQuery("#reviewrateAlert").hide();
               jQuery(this).addClass('active');
               jQuery(this).prevAll().addClass('active');
               jQuery(this).nextAll().removeClass('active');
			    var dataprtext=jQuery(this).attr('data-prtext');
				jQuery("#reviewrateText").text(dataprtext);
				jQuery("#reviewrate").val(jQuery(".review_star_li.active").length);
            });

	 jQuery("#review-form-el").on('submit',function(e) {
				e.preventDefault();

			jQuery("#frmresponse_review").text("");
                // Custom validation
                var isValid = true;
				var reviewername = jQuery("#reviewername").val();
                var reviewWrte = jQuery("#review-wrte").val();
                var reviewrate = jQuery("#reviewrate").val();

                if (reviewrate == "" || reviewrate == 0 || reviewrate == null) {
                  jQuery("#reviewrateAlert").show();
                    isValid = false;
                    return;
                }else{
					jQuery("#reviewrateAlert").hide();
				}


                if (isValid) {
                     jQuery(".rw-submit-btn").attr('disabled',true);
                    jQuery.ajax({
                        type: "POST",
                        dataType: "json",
                        url: siteData.site_url + '/wp-admin/admin-ajax.php',
                        data: {
                            action: "create_checkout_review",
                            reviewrate: reviewrate,
                            reviewername: reviewername,
                            reviewWrte: reviewWrte
                        },
                        success: function(response) {
                             jQuery(".rw-submit-btn").removeAttr('disabled');
                           if(response.success == true || response.success == "true"){
							    jQuery('.review_star_li').removeClass('star-hovered').removeClass('active');
							   	jQuery("#reviewername").val("");
								jQuery("#review-wrte").val("");
								jQuery("#reviewrate").val("");
                               	jQuery("#frmresponse_review").text(response.message);
                               	 jQuery("#frmresponse_review").addClass('success');
                               	  jQuery("#frmresponse_review").removeClass('error');
                               	//  jQuery(".revw-lst-wrapper").prepend(response.responsehtml);
                               	//getNewRivewRating();

                           }else{
                              	jQuery("#frmresponse_review").text(response.message);
                              		 jQuery("#frmresponse_review").removeClass('success');
                               	  jQuery("#frmresponse_review").addClass('error');
                           }

                           setTimeout(function() {
                                jQuery("#frmresponse_review").text("");
                            }, 5000); // 5000 milliseconds = 5 seconds

                        },
                        error: function(error) {
                            // Handle error
                            console.error(error);
                        }
                    });
                }
            });
		 jQuery(".add__review_btn").on("click", function (e) {
                e.preventDefault();
                // Move to the section with ID 'review-form'
				// window.dispatchEvent(new Event('resize'));
                 var headerheight=0;
				  if(jQuery('header').hasClass("elementor-sticky--effects")){
					  headerheight=jQuery('header').outerHeight();
				  }
                jQuery('html, body').animate({
                    scrollTop: jQuery("#review-form").offset().top - headerheight
                }, 1000);
            });
});
// function smoothelFocus(selector) {
//     var element = jQuery(selector);
//     var parelement = element.closest(".elementor-top-section");
//
//     // Check if the element exists on the page
//     if (parelement.length > 0) {
//       // Animate a smooth scroll to the element
// 	  //window.dispatchEvent(new Event('resize'));
// 	  var headerheight=0;
// 	  if(jQuery('header').hasClass("elementor-sticky--effects")){
// 		  headerheight=jQuery('header').outerHeight();
// 	  }
//
//       jQuery('html, body').animate({
//         scrollTop: parelement.offset().top- headerheight
//       }, 800); // Adjust the duration as needed
//
//       setTimeout(function() {
//      element.focus();
//     }, 800); // Adjust the duration as needed
//     }
//   }
  function roundToOneDecimalPlace(number) {
    return Number(number.toFixed(1));
}

function getNewRivewRating(){
	 var reviewElements = jQuery('.revw-lst');

    var totalRatingsJS = 0;
    var maxRatingPost = reviewElements.length;

    // Iterate over each element and sum up the normalized ratings
		reviewElements.each(function( index ) {
        var rating = parseInt(jQuery(this).attr('data-rating'));
        var normalizedRating = isNaN(rating) ? 0 : rating;
        totalRatingsJS += normalizedRating;
    });
	 var overall_average_rating = totalRatingsJS / maxRatingPost;
	  overall_average_rating = roundToOneDecimalPlace(overall_average_rating);
	  jQuery(".total_review_rating").html(overall_average_rating.toFixed(1));
	  generateRatingStars(overall_average_rating);

}




// Function to generate the HTML for the stars based on overall_average_rating
function generateRatingStars(overall_average_rating) {

	 var total_star_li = jQuery('.total_star_li');
	 var i=1;
	 var avgtext="";
	total_star_li.each(function( index ) {
		if(overall_average_rating >= i){
		jQuery(this).addClass('active');
		 avgtext = jQuery(this).attr('data-prtext');
		}else{
			jQuery(this).removeClass('active');
		}
		i++;
	});
	jQuery('.totalstarsText').html(avgtext);
}

let myExpInterval = setInterval(function(){
    let expressDivider = jQuery(".fscheckout_expressbtn_ct .express-divider");

    if(expressDivider.length > 0) {
        jQuery('.fscheckout_expressbtn_ct legend').contents().unwrap().wrap('<span class="express-title">');

        const pageTranslations = {
            1214: {
				or: 'Oder',
				pp: 'PayPal, schnelle und sichere Zahlung'
			}, // de
            //9917: 'Ou', // pt-pt
            15: {
				or: 'Or',
				pp: 'PayPal, fast and secure payment'
			}, // en
            1398: {
				or: 'Of',
				pp: 'PayPal, fast and secure payment'
			}, // nl
            1406: {
				or: 'Of',
				pp: 'PayPal, fast and secure payment'
			}, // be-nl
            1400: {
				or:'Ou',
				pp: 'PayPal, paiement rapide et sécurisé'
			}, //fr
            1404: {
				or: 'Ou',
				pp: 'PayPal, fast and secure payment'
			} // be-fr
        };

		// payment_method_ppcp

        for (const [pageId, text] of Object.entries(pageTranslations)) {
            jQuery(`.page-id-${pageId} .fscheckout_expressbtn_ct .express-divider`).text(text.or);
			jQuery(`.page-id-${pageId} .payment_box.payment_method_ppcp p`).text(text.pp);
        }
        clearInterval(myExpInterval);
    }
}, 300);

jQuery(document).ready(function($) {
    const DOMAIN = 'lumilean.io';
    const domainPattern = DOMAIN.replace(/\./g, '\\.');

    const checkoutRegex = new RegExp(
        '^'
        + '(?:https:\\/\\/' + domainPattern + ')?'
        + '(?:\\/(?:[a-zA-Z]{4}|[a-zA-Z]{2}(?:-[a-zA-Z]{2})?))?'
        + '\\/checkout'
        + '\\/?'
        + '$'
    );

    function getCookie(name) {
        let match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
        if (match) {
            return decodeURIComponent(match[2]);
        }
        return null;
    }

    let redirectUrl = getCookie('redirectUrl');

    $('a').on('click', function(e) {
        if (!redirectUrl) return;

        let href = $(this).attr('href') || '';

        if (checkoutRegex.test(href)) {
            e.preventDefault();
            window.location.href = redirectUrl;
        }
    });
});


