HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: /var/www/html/CW-techs/wp-content/themes/cw-techs/js/custom-ajax.js
jQuery(document).ready(function ($) {
    // Get URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    
    // Check if 'message=success' exists
    if (urlParams.get('message') === 'success') {
        toastr.success('Login successful!');
        // Remove the parameter from the URL to prevent repeated alerts
        window.history.replaceState(null, null, window.location.pathname);
    }
    $('.proceed-to-checkout').on('click', function (e) {
        const cartCount = parseInt($('.woocommerce .cart .quantity, .badge').first().text());

        if (isNaN(cartCount) || cartCount <= 0) {
        e.preventDefault(); // stop redirect
        toastr.error('Your cart is empty. Please add items before proceeding to checkout.');
        }
    });
});
jQuery(document).ready(function($) {
    $('#signupForm').parsley();
    $('#signUpBtn').on('click', function (e) {
       
        e.preventDefault();
        
        if ($('#signupForm').parsley().validate()) {
            var signUpBtn = $(this);
            var originalText = signUpBtn.text();
            signUpBtn.text('Submitting...').prop('disabled', true);

            var formData = new FormData($('#signupForm')[0]);
            formData.append('action', 'register_user');
            // formData.append('security', ajax_obj.register_nonce);

            $.ajax({
                url: ajax_obj.ajaxurl,
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    signUpBtn.text(originalText).prop('disabled', false);
                    // Show the result container again if previously faded out
                    // $('#signup-form-result').stop(true, true).show();
                    if (response.success) {
                        // Reset form
                        $('#signupForm')[0].reset();
                        // $('#signup-form-result').html('<div class="alert alert-success">' + response.data.message + '</div>');
                        toastr.success(response.data.message);
                    } else {
                        var errorMessage = response.data && response.data.message ? response.data.message : 'Unknown error occurred.';
                        // $('#signup-form-result').html('<div class="alert alert-danger">' + errorMessage + '</div>');
                        toastr.error(errorMessage);
                    }
                },
                error: function () {
                    signUpBtn.text(originalText).prop('disabled', false);
                    // $('#signup-form-result').html('<div class="alert alert-danger">There was an error processing your request. Please try again.</div>');
                   toastr.error('There was an error processing your request. Please try again.');
                }
            });
        }
    });
    // Login
    jQuery('#loginForm').parsley();

    jQuery('#loginBtn').on('click', function (e) {
        e.preventDefault(); // Prevent default form submission
        
        if (jQuery('#loginForm').parsley().validate()) { // Check if the form is valid
        var loginBtn = jQuery(this);
        var originalLogin = loginBtn.text();

        loginBtn.text('Logging in...').prop('disabled', true);
        var formData = new FormData(jQuery('#loginForm')[0]);
        formData.append('action', 'login_user');
        //formData.append('security', ajax_obj.login_nonce);  // Add nonce to form data

            jQuery.ajax({
                url: ajax_obj.ajaxurl,
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                
                console.log(response);
                //   alert(response.status);
                if (response.success) {  // Check success field instead of status
                    // loginBtn.text(originalLogin).prop('disabled', false);
                    // $("#loginBtn").prop("disabled", false).text("Login");
                    if (response.data.redirect) {
                        window.location.href = response.data.redirect + '?message=success';
                    }
                } else {
                    // loginBtn.text(originalLogin).prop('disabled', false);
                    $("#loginBtn").prop("disabled", false).text("Login");
                    var errorMessage = response.data && response.data.message ? response.data.message : 'Unknown error occurred.';
                    // jQuery('#login-form-result').html('<div class="alert alert-danger">' + errorMessage + '</div>');
                    toastr.error(errorMessage);
                    // Automatically remove the error message after 3 seconds
                    
                }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.error('AJAX Error:', textStatus, errorThrown); // Log error details
                    console.error('Response Text:', jqXHR.responseText); // Log the server's response
                    loginBtn.text(originalLogin).prop('disabled', false);
                    jQuery('#login-form-result').html('<div class="alert alert-danger">There was an error processing your request. Check console for details.</div>');
                }
            });
        }
    });
});
// Function to validate the input
    function validateName(input) {
        let regex = /^[A-Za-z][A-Za-z '’-]*$/;
        if (!regex.test(input.value)) {
            input.value = input.value.slice(0, -1); // Remove invalid character
        }
    }

jQuery(document).ready(function($) {
    $('.fav-list').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();

        var button = $(this);
        var product_id = button.data('product');
        if (ajax_obj.is_logged_in != '1') {
            toastr.error("Log in to add this to your favorites.");
            return;
        }
        $.post(ajax_obj.ajaxurl, {
            action: 'toggle_favorite',
            product_id: product_id
        }, function(response) {
            if (response.success) {
                if (response.data.action === 'added') {
                    toastr.success('Added to Favorites');
                } else {
                    toastr.info('Removed from Favorites');
                }

                setTimeout(function(){
                    location.reload();
                }, 1500);
            } else {
                toastr.error(response.data);
            }
        });
    });
    // Handle Remove Favorite
    $('.remove-favorite').on('click', function(e) {
        e.preventDefault();
        var button = $(this);
        var product_id = button.data('product-id');

        $.post(ajax_obj.ajaxurl, {
            action: 'toggle_favorite',
            product_id: product_id
        }, function(response) {
            if (response.success) {
                // Remove the product visually
                button.closest('.listing-blks').fadeOut('slow', function() { 
                    $(this).remove(); 
                });
                toastr.info("Removed from favorites");
                setTimeout(function(){
                    location.reload();
                }, 1500);
            } else {
                toastr.error(response.data);
            }
        });
    });
// Move to cart functionality
    $('.move-to-cart-btn').on('click', function(e) {
        e.preventDefault();
        var button = $(this);
        var product_id = $(this).data('product-id');

        $.post(ajax_obj.ajaxurl, {
            action: 'move_to_cart',
            product_id: product_id
        }, function(response) {
           if (response.success) {
                toastr.success("Product moved to cart!");

                // Optional: remove item from favorites after moving to cart
                // button.closest('.listing-blks').fadeOut('slow', function() { 
                //     $(this).remove(); 
                // });
                setTimeout(function(){
                    location.reload();
                }, 1500);
            } else {
                toastr.error(response.data);
            }
        });
    });
    $('#forgot-password-form').on('submit', function (e) {
        e.preventDefault();
        if (jQuery('#forgot-password-form').parsley().validate()) { 
            let email = $('#user_email').val();

            $.ajax({
                url: ajax_obj.ajaxurl,
                type: 'POST',
                data: {
                    action: 'handle_forgot_password',
                    user_email: email
                },
                beforeSend: function() {
                    $("#forget_id").prop("disabled", true).text("Submitting...");
                },
                success: function (response) { 
                    $("#forget_id").prop("disabled", false).text("Forgot Password");
                    if (response.success) {
                        // ✅ Green success message
                        $('#forgot-password-form')[0].reset();
                        toastr.success(response.data.message);
                        // setTimeout(function () {
                        //     location.reload();
                        // }, 3000);
                    } else {
                        toastr.error(response.data.message);
                        // $('#forgot-form-result').html('<div class="alert alert-danger">' + response.data.message + '</div>');
                    }
                }
            });
        }
    });
});
jQuery(document).ready(function ($) {
    function getQueryParam(param) {
        let urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
    }

    let reset_key = getQueryParam('key');
    let user_login = getQueryParam('login');

    $('#reset_key').val(reset_key);
    $('#user_login').val(user_login);

    $('#reset-password-form').on('submit', function (e) {
        e.preventDefault();
        if (jQuery('#reset-password-form').parsley().validate()) { 
            let new_password = $('#new_password').val();
            let confirm_password = $('#confirm_password').val();

            if (new_password !== confirm_password) {
                $('#reset-password-response').html('<p style="color:red;">Passwords do not match.</p>');
                return;
            }

            $.ajax({
                url: ajax_obj.ajaxurl,
                type: 'POST',
                data: {
                    action: 'handle_password_reset',
                    new_password: new_password,
                    reset_key: reset_key,
                    user_login: user_login
                },
                beforeSend: function() {
                    $("#reset-btn").prop("disabled", true).text("Submitting...");
                },
                success: function (response) {
                    if (response.success) {
                        $("#reset-btn").prop("disabled", false).text("Reset Password");
                        toastr.success(response.data.message);
                        // $('#reset-form-result').html('<div class="alert alert-success">' + response.data.message + '</div>');
                        setTimeout(function () {
                            window.location.href = '/login'; // Change this to your actual login page URL
                        }, 3000);
                    } else {
                        $("#reset-btn").prop("disabled", false).text("Reset Password");
                        // $('#reset-form-result').html('<div class="alert alert-danger">' + response.data.message + '</div>');
                        toastr.error(response.data.message);
                    }
                }
            });
        }
    });
});
jQuery(document).ready(function($) {

  // Handle plus
  $('.plus').on('click', function() {
    var cartItem = $(this).closest('.cart-item');
    var cartItemKey = cartItem.data('cart-item-key');
    var currentQty = parseInt(cartItem.find('.current-qty').text());
    var newQty = currentQty + 1;

    updateCart(cartItemKey, newQty, 'added');
  });

  // Handle minus
  $('.minus').on('click', function() {
    var cartItem = $(this).closest('.cart-item');
    var cartItemKey = cartItem.data('cart-item-key');
    var currentQty = parseInt(cartItem.find('.current-qty').text());
    var newQty = Math.max(currentQty - 1, 1);

    if (currentQty > 1) {
        var newQty = currentQty - 1;
        updateCart(cartItemKey, newQty, 'decreased');
    } else {
        toastr.info('Minimum quantity is 1');
    }
  });

  // Handle delete
//   $('.delete').on('click', function() {
//     var cartItem = $(this).closest('.cart-item');
//     var cartItemKey = cartItem.data('cart-item-key');

//     updateCart(cartItemKey, 0, 'removed');
//   });

  function updateCart(cartItemKey, qty, actionType) {
    $.ajax({
      type: 'POST',
      url: ajax_obj.ajaxurl,
      data: {
        action: 'update_cart_item_qty',
        cart_item_key: cartItemKey,
        quantity: qty
      },
      success: function(response) {
        if (response.success) {

          // Show toastr message based on action
          if(actionType === 'added') {
            toastr.success('Quantity increased!');
          } else if(actionType === 'decreased') {
            toastr.info('Quantity decreased!');
          } else if(actionType === 'removed') {
            toastr.warning('Item removed from cart!');
          }

          // Reload after small delay to allow toastr to show
          setTimeout(function() {
            location.reload();
          }, 1000);

        } else {
          toastr.error(response.data);
        }
      },
      error: function() {
        toastr.error('Something went wrong. Please try again.');
      }
    });
  }
  // Capture cart item key when delete button is clicked
$('.delete').on('click', function() {
    $('#removeModalDelete').modal('show');
    var cartItem = $(this).closest('.cart-item');
    var cartItemKey = cartItem.data('cart-item-key');
    $('#confirmRemoveKey').val(cartItemKey);
});

// Handle confirmation remove
$('.remove-confirm').on('click', function() {
  var cartItemKey = $('#confirmRemoveKey').val();

  $.ajax({
    type: 'POST',
    url: ajax_obj.ajaxurl,
    data: {
      action: 'update_cart_item_qty',
      cart_item_key: cartItemKey,
      quantity: 0
    },
    success: function(response) {
      if (response.success) {
        toastr.warning('Item removed from cart!');
        $('#removeModalDelete').modal('hide');
        setTimeout(function() {
          location.reload();
        }, 1000);
      } else {
        toastr.error(response.data);
      }
    },
    error: function() {
      toastr.error('Something went wrong.');
    }
  });
});


});
// Contact form submission
jQuery(document).ready(function ($) {
	$('#custom-contact-form').parsley(); // Initialize Parsley validation

	$('.saveContactUs').on('click', function (e) {
		e.preventDefault();

		if ($('#custom-contact-form').parsley().validate()) {
			var buttonContact = $(this);
			var originalTextContact = buttonContact.text();
			buttonContact.text('Sending...').prop('disabled', true);

			var formData = new FormData($('#custom-contact-form')[0]);
			formData.append('action', 'submit_contact_form');

			$.ajax({
				url: ajax_obj.ajaxurl,
				type: 'POST',
				data: formData,
				contentType: false,
				processData: false,
				success: function (response) {
					buttonContact.text(originalTextContact).prop('disabled', false);

					if (response.success) {
						toastr.success(response.data.message);
						$('#custom-contact-form')[0].reset(); // Reset the form
						$('#custom-contact-form').parsley().reset()
					} else {
						toastr.error(response.data.message);
					}
				},
				error: function () {
					buttonContact.text(originalTextContact).prop('disabled', false);
                    toastr.error('There was an error processing your request. Please try again.');
				}
			});
		}
	});
});
// Newsletter form submission
jQuery(document).ready(function($) {
    $('#newsletter-form').on('submit', function(event) {
        event.preventDefault();
        if ($('#newsletter-form').parsley().validate()) {
            var email = $('#newsletter-email').val();
            var $button = $('.newsletter-button');


            // Show loader state on button
            $button.prop('disabled', true).html('Subscribing...');

            $.ajax({
                url: '/wp-admin/admin-ajax.php',
                type: 'POST',
                data: {
                    action: 'newsletter_subscribe',
                    email: email
                },
                success: function(response) {
                    if (response.success == true) {
                        
                        $('#newsletter-email').val('');
                        toastr.success(response.data.message);
                    } else {
                        
                        $('#newsletter-email').val('');
                        toastr.error(response.data.message);
                    }
                },
                error: function() {
                    toastr.error('Something went wrong. Please try again.');
                    // $('.error-msg').html('Something went wrong. Please try again.').fadeIn();
                },
                complete: function() {
                    // Restore button state
                    $button.prop('disabled', false).html('Subscribe');
                }
            });
        }
    });
});
// Final Form Validation on Submit
function validateForm() {
    validatePassword();
    validateConfirmPassword();

    let passwordError = document.getElementById("password-error").textContent;
    let confirmError = document.getElementById("confirm-password-error").textContent;

    if (passwordError || confirmError) {
        return false; // Prevent form submission if errors exist
    }
    return true; // Allow form submission if no errors
}


// document.getElementById('email').addEventListener('input', function(e) {
//     // Restrict input to alphanumeric characters, @, and .
//     let input = e.target.value;

//     // Remove any invalid character
//     input = input.replace(/[^a-zA-Z0-9@.+]/g, '');

//     // Update the input field with the restricted value
//     e.target.value = input;
//   });


//------------------------------------Search --------------------------------------------
document.addEventListener("click", function (event) {
  const searchInput = document.querySelector(".product-search");
  const suggestionsBox = document.querySelector(".product-suggestions");

  // If click is outside the search input and suggestions box, hide the suggestions
  if (
    !searchInput.contains(event.target) &&
    !suggestionsBox.contains(event.target)
  ) {
    suggestionsBox.style.display = "none";
  }
});

jQuery(document).ready(function ($) {
  $('.product-suggestions').hide();

//    $('.product-search').on('keyup', function () {
//     let query = $(this).val().trim();

//     if (query.length > 1) {
//       $.ajax({
//         url: ajax_obj.ajaxurl,
//         type: 'POST',
//         data: {
//           action: 'autocomplete_products',
//           term: query
//         },
//         success: function (response) {
//           $('.product-suggestions').html('');
          
//           let data = JSON.parse(response);

//           if (data.length > 0) {
//             data.forEach(function (product) {
//               $('.product-suggestions').append('<div class="suggestion-item" data-url="' + product.url + '">' + product.name + '</div>');
//             });
//             $('.product-suggestions').show();
//           } else {
//             $('.product-suggestions').html('<div class="no-result">No products found</div>').show();
//           }
//         }
//       });
//     } else {
//       $('.product-suggestions').html('').hide();
//     }
//   });

//   // 👆 Handle click on suggestion
//   $(document).on('click', '.suggestion-item', function () {
//     const url = $(this).data('url');
//     if (url) {
//       window.location.href = url;
//     }
//   });

//   // 🔘 Handle search button click
//   $('.search-btn').on('click', function (e) {
//     e.preventDefault();
//     const searchQuery = $('.product-search').val().trim();

//     if (searchQuery !== '') {
//       // Redirect to search results (change to your desired URL structure)
//       window.location.href = '/search/?q=' + encodeURIComponent(searchQuery);
//     }
//   });
  

//   // Click suggestion to go to product
//   $('.product-suggestions').on('click', 'div', function () {
//     window.location.href = $(this).data('url');
//   });
});

document.addEventListener("DOMContentLoaded", function () {
  const searchInput = document.querySelector(".product-search");
  const suggestionsBox = document.querySelector(".product-suggestions");
  let timeout;

  // Show previous search if URL has ?search=...
  const urlParams = new URLSearchParams(window.location.search);
  const searchQuery = urlParams.get("search") || urlParams.get("s");
  if (searchQuery && searchInput) {
    searchInput.value = searchQuery;
  }

  searchInput.addEventListener("keyup", function () {
    const query = this.value.trim();
    clearTimeout(timeout);

    if (query.length > 2) {
      timeout = setTimeout(() => {
        suggestionsBox.innerHTML = '<p style="padding:10px;">Searching...</p>';
        suggestionsBox.style.display = "block";

        fetch(`/wp-admin/admin-ajax.php?action=product_suggestions&query=${encodeURIComponent(query)}`)
          .then((res) => res.text())
          .then((html) => {
            suggestionsBox.innerHTML = html;
            suggestionsBox.style.display = "block";

            // Attach click event to each <a> inside the suggestion list
            const links = suggestionsBox.querySelectorAll(".suggestion-list a");
            links.forEach(link => {
              link.addEventListener("click", function (e) {
                e.preventDefault(); // Prevent normal navigation

                const selectedText = this.textContent.trim();
                const targetURL = new URL(this.href);
                targetURL.searchParams.set('search', selectedText); // Add ?search=...

                window.location.href = targetURL.toString(); // Redirect manually
              });
            });
          });
      }, 300);
    } else {
      suggestionsBox.style.display = "none";
    }
  });
});







jQuery(document).ready(function($) {
    function fetchFilteredProducts() {
        let data = {
            action: 'filter_products',
            // nonce: product_filter_params.nonce,
            categories: [],
            brands: [],
            stock: [],
            rating: [],
            discount: [],
            min_price: $('#min_price').val(),
            max_price: $('#max_price').val()
        };

        $('input[name="brand[]"]:checked').each(function() {
            data.brands.push($(this).val());
        });

        $('input[name="stock[]"]:checked').each(function() {
            data.stock.push($(this).val());
        });

        $('input[name="rating[]"]:checked').each(function() {
            data.rating.push($(this).val());
        });

        $('input[name="category[]"]:checked').each(function() {
            data.categories.push($(this).val());
        });
        $('input[name="discount[]"]:checked').each(function() {
            data.discount.push($(this).val());
        });
        $.post(ajax_obj.ajaxurl, data, function(response) {
            $('.listing-products').html(response);
        });
    }

    $('input[type="checkbox"], #min_price, #max_price').on('change', function() {
        fetchFilteredProducts();
    });
    // Initialize price range slider
    $("#slider-range").slider({
        range: true,
        min: 0,
        max: 1000000,
        values: [0, 1000000],
        slide: function(event, ui) {
            $('#min_price').val(ui.values[0]);
            $('#max_price').val(ui.values[1]);
        },
        change: function(event, ui) {
            fetchFilteredProducts();
        }
    });

    // Keep slider in sync if inputs are edited manually
    $('#min_price, #max_price').on('input change', function () {
        const minVal = parseInt($('#min_price').val()) || 0;
        const maxVal = parseInt($('#max_price').val()) || 1000000;
        $("#slider-range").slider('values', [minVal, maxVal]);
    });
});
jQuery(document).ready(function($) {
        $('#custom-review-form').parsley();

        $('#custom-review-form').on('submit', function(e) {
            e.preventDefault();
            const form = $(this);

            if (form.parsley().isValid()) {
                const formData = {
                    action: 'submit_custom_product_review',
                    rating: $('#rating_cust').val(),
                    review: $('#review').val(),
                    product_id: $('input[name="product_id"]').val()
                };

                $.ajax({
                    url: ajax_obj.ajaxurl,
                    type: 'POST',
                    data: formData,
                    beforeSend: function() {
                        $("#review-btn").prop("disabled", true).text("Submitting...");
                    },
                    success: function(response) {
                        $("#review-btn").prop("disabled", false).text("Submit Review");
                        if (response.success) {
                            form[0].reset();
                            form.parsley().reset();
                            toastr.success(response.data.message || 'Thank you for your review!');
                        } else {
                            toastr.error(response.data.message || 'Review submission failed.');
                            form[0].reset();
                            form.parsley().reset();
                        }
                    },
                    error: function() {
                        toastr.error('An unexpected error occurred.');
                    }
                });
            }
        });
    });
jQuery(document).ready(function ($) {
       // Delivery button
        $('.select-address-btn').on('click', function() {
            $('.address-box').removeClass('address-active');
            $(this).closest('.address-box').addClass('address-active');

            let index = $(this).data('index');
            let selected = window.savedAddresses[index];
            // console.log(selected);
            // Optional: Autofill WooCommerce checkout fields
            if (selected) {
                let fullName = selected.label.trim().split(" ");
                let firstName = fullName[0] || '';
                let lastName = fullName.slice(1).join(" ") || '';
                $('input[name="billing_first_name"]').val(firstName);
                $('input[name="billing_last_name"]').val(lastName);
                $('input[name="billing_address_1"]').val(selected.address_line);
                $('input[name="billing_city"]').val(selected.city);
                $('input[name="billing_postcode"]').val(selected.postcode);
                $('select[name="billing_country"]').val(selected.country).trigger('change');
                $('input[name="billing_state"]').val(selected.state);
            }
        });
});