File: /var/www/html/video-rental/wp-content/themes/video-rental-olds/js/custom_js.js
// 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 ($) {
// 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);
}
});
jQuery(document).ready(function($) {
$('.register-link').on('click', function(e) {
$('#signup-tab').trigger('click');
});
});
// jQuery(document).ready(function ($) {
// $('.rent-now-btn').on('click', function () {
// if (isUserLoggedIn) {
// const modal = new bootstrap.Modal(document.getElementById('modalStep1'));
// modal.show();
// } else {
// window.location.href = '/login';
// }
// });
// });
jQuery(document).ready(function ($) {
// Remove the 'logged_out' param from the URL
// const newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
// window.history.replaceState({}, document.title, newUrl);
// Submit button triggers real logout
$('#loggedOut-btn').on('click', function () {
const logoutLink = $('#trueLogout').attr('href');
if (logoutLink) {
window.location.href = logoutLink;
}
});
});
jQuery(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) {
// // Read current URL parameters
// const urlParams = new URLSearchParams(window.location.search);
// const continueRent = urlParams.get('continue_rent');
// const postId = urlParams.get('post_id');
// // Default redirect
// let redirectUrl = response.data.redirect;
// // If continue_rent & post_id exist, override redirect
// if (continueRent && postId) {
// redirectUrl = `${ajax_obj.site_url}/home?continue_rent=1&post_id=${postId}`;
// }
// // Show success message
// toastr.success(response.data.message);
// // Redirect after delay
// setTimeout(function () {
// window.location.href = redirectUrl;
// }, 2000);
const urlParams = new URLSearchParams(window.location.search);
const continueRent = urlParams.get('continue_rent');
const licence = urlParams.get('licence');
let redirectUrl = response.data.redirect;
let thankYouText = 'Thank you for registering.';
if (window.location.pathname.includes('login')) {
thankYouText = 'Thank you for logging in.';
}
// Optional: If you want to redirect on modal button click
if (continueRent && licence) {
redirectUrl = `${ajax_obj.site_url}/home?continue_rent=1&licence=${licence}`;
toastr.success(response.data.message);
setTimeout(function () {
window.location.href = redirectUrl;
}, 2000);
}
else
{
// Set thank you message
$('#thankYouMessage').text(thankYouText);
// Show the modal
$('#thankYouModal').modal('show');
}
} else {
const errorMessage = response.data && response.data.message ? response.data.message : 'Unknown error occurred.';
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.');
}
});
}
});
function handleLoginForm() {
$('#loginForm').on('submit', function (e) {
e.preventDefault();
const form = $(this);
// Validate using Parsley
if (!form.parsley().isValid()) {
return;
}
const email = $('#email').val().trim();
const password = $('#passwordField').val().trim();
const remember = $('#rememberMe').is(':checked');
// Clear old error messages
$('.error-msg').text('');
$.ajax({
url: ajax_obj.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'login_user',
email: email,
password: password,
remember: remember
},
success: function (response) {
console.log(response);
// alert(response.status);
if (response.success) {
let redirectUrl = response.data.redirect;
// Read current URL parameters
const urlParams = new URLSearchParams(window.location.search);
const continueRent = urlParams.get('continue_rent');
const licence = urlParams.get('licence');
// If continue_rent is set, add it to the redirect URL
// if (continueRent && postId) {
// redirectUrl += `?continue_rent=1&post_id=${postId}`;
// }
let thankYouText = 'Thank you for Logging in.';
if (continueRent && licence) {
redirectUrl = `${ajax_obj.site_url}/home?continue_rent=1&licence=${licence}`;
window.location.href = redirectUrl;
}
else
{
$('#thankYouMessage').text(thankYouText);
// Show the modal
$('#thankYouModal').modal('show');
}
} else {
$("#loginBtn").prop("disabled", false).text("Login");
const errorMessage = response.data && response.data.message ? response.data.message : 'Unknown error occurred.';
toastr.error(errorMessage);
}
},
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>');
}
});
});
// Optional: Back to home button
$('.back-btn').on('click', function () {
window.location.href = ajax_obj.redirect_url;
});
}
// Call the function
handleLoginForm();
});
// 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.');
}
});
}
});
});
jQuery(document).ready(function($) {
$('#ChanagePasswordModal').on('hidden.bs.modal', function() {
// Reset the form
$('#password-form')[0].reset();
$('#password-form').parsley().reset();
});
$('#editProfileModal').on('hidden.bs.modal', function() {
// Reset the form
$('#edit-profile-form')[0].reset();
$('#edit-profile-form').parsley().reset();
});
// Initialize Parsley validation on the form
$('#password-form').parsley();
$('#password-form').on('submit', function(e) {
e.preventDefault();
if ($(this).parsley().isValid()) {
var formData = $(this).serialize();
$.ajax({
url: ajax_obj.ajaxurl, // WordPress AJAX URL
type: "POST",
data: formData + '&action=change_user_password', // include action
beforeSend: function() {
// Optional: disable submit button or show loader
$('#password-form button[type="submit"]').prop('disabled', true);
},
beforeSend: function() {
$("#chngepswd-btn").prop("disabled", true).text("Submitting...");
},
success: function(response) {
$("#chngepswd-btn").prop("disabled", false).text("Submit");
// Enable button again
console.log('Redirect URL:', response.data.logout_url);
$('#password-form button[type="submit"]').prop('disabled', false);
if (response.success) {
// Hide any open modal
$('.modal.show').modal('hide');
// Show success modal
// setTimeout(function() {
// $('#removeModal').modal('show');
// }, 500);
const message = response.data.message;
const logoutUrl = response.data.logout_url;
$('#removeModal').modal('show');
setTimeout(function() {
window.location.href = logoutUrl;
}, 3000);
} else {
toastr.error(response.data.message);
$('#password-form')[0].reset();
$('#password-form').parsley().reset();
}
},
error: function(xhr) {
$('#password-form button[type="submit"]').prop('disabled', false);
alert('Something went wrong.');
}
});
}
});
});
jQuery(document).ready(function($) {
$('#edit-profile-form').parsley();
$('#edit-profile-form').on('submit', function(e) {
e.preventDefault();
if ($(this).parsley().isValid()) {
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: ajax_obj.ajaxurl, // WordPress will provide this object
data: {
action: 'update_user_profile',
form_data: formData
},
beforeSend: function () {
$("#profile-btn").prop("disabled", true).text("Submitting...");
},
success: function(response) {
$("#profile-btn").prop("disabled", false).text("Submit");
if (response.success) {
toastr.success('Profile updated successfully!');
$('#editProfileModal').modal('hide');
setTimeout(function(){
location.reload();
}, 1500);
} else {
toastr.error(response.data);
}
},
error: function() {
toastr.error('Something went wrong.');
}
});
}
});
$('#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_passwords').val();
// console.log(new_password);
// console.log(confirm_password);
if (new_password !== confirm_password) {
toastr.error('Passwords do not match.');
// $('#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($) {
$('#img').on('change', function() {
var file_data = $('#img').prop('files')[0];
var form_data = new FormData();
form_data.append('profile_image', file_data);
form_data.append('action', 'upload_profile_image');
// form_data.append('_ajax_nonce', profile_image_vars.nonce);
$.ajax({
url: ajax_obj.ajaxurl,
type: 'POST',
data: form_data,
contentType: false,
processData: false,
success: function(response) {
if (response.success) {
$('#profile-picture').attr('src', response.data.image_url);
toastr.success('Profile image updated');
} else {
toastr.error(response.data.message);
}
}
});
});
});
// Initialize Parsley on both forms
$('#step1Form').parsley();
$('#step2Form').parsley();
document.getElementById('toStep2').addEventListener('click', function () {
// const step1Form = document.getElementById('step1Form');
// if (!step1Form.checkValidity()) {
// step1Form.reportValidity();
// return;
// }
// const modal1 = bootstrap.Modal.getInstance(document.getElementById('modalStep1'));
// modal1.hide();
// const modal2 = new bootstrap.Modal(document.getElementById('modalStep2'));
// modal2.show();
const form = $('#step1Form');
if (form.parsley().validate()) {
const modal1 = bootstrap.Modal.getInstance(document.getElementById('modalStep1'));
modal1.hide();
const modal2 = new bootstrap.Modal(document.getElementById('modalStep2'));
modal2.show();
}
});
document.getElementById('submitRental').addEventListener('click', function (e) {
const step1Data = new FormData(document.getElementById('step1Form'));
e.preventDefault();
const step2Form = $('#step2Form');
if (!step2Form.parsley().validate()) {
return;
}
const step2Data = new FormData(document.getElementById('step2Form'));
for (const [key, value] of step2Data.entries()) {
step1Data.append(key, value);
}
// Button reference
const rentalBtn = $('#submitRental');
const originalText = rentalBtn.text();
rentalBtn.text('Submitting...').prop('disabled', true);
fetch('/wp-admin/admin-ajax.php?action=handle_rent_video', {
method: 'POST',
body: step1Data
})
.then(res => res.json())
.then(data => {
const modal2El = document.getElementById('modalStep2');
const modal2Instance = bootstrap.Modal.getInstance(modal2El);
if (modal2Instance) {
modal2Instance.hide();
}
rentalBtn.text(originalText).prop('disabled', false);
if (data.success) {
const successModalEl = document.getElementById('myModal');
if (successModalEl) {
const successModal = new bootstrap.Modal(successModalEl);
successModal.show();
}
} else {
const errorMsg = data.message || 'Payment failed. Please try again.';
// ✅ Create Toast HTML if not exists
let toastContainer = document.getElementById('toast-container');
if (!toastContainer) {
toastContainer = document.createElement('div');
toastContainer.id = 'toast-container';
toastContainer.style.position = 'fixed';
toastContainer.style.top = '20px';
toastContainer.style.right = '20px';
toastContainer.style.zIndex = '9999';
document.body.appendChild(toastContainer);
}
const toast = document.createElement('div');
toast.className = 'toast align-items-center text-white bg-danger border-0 show';
toast.setAttribute('role', 'alert');
toast.setAttribute('aria-live', 'assertive');
toast.setAttribute('aria-atomic', 'true');
toast.style.minWidth = '250px';
toast.style.marginBottom = '10px';
toast.innerHTML = `
<div class="d-flex">
<div class="toast-body">
${errorMsg}
</div>
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
`;
toastContainer.appendChild(toast);
setTimeout(() => {
toast.remove();
}, 5000);
}
});
});
// document.getElementById('submitStep2').addEventListener('click', function () {
// const form = document.getElementById('step2Form');
// if ($(form).parsley().validate()) {
// // Continue to AJAX or show success modal
// console.log('Card form valid. Proceed to payment.');
// }
// });
document.addEventListener('DOMContentLoaded', function () {
const expiryInput = document.querySelector('input[name="expiry"]');
expiryInput.addEventListener('input', function (e) {
let value = this.value.replace(/\D/g, ''); // Remove non-digits
if (value.length > 4) value = value.substr(0, 4);
if (value.length >= 3) {
this.value = value.substr(0, 2) + '/' + value.substr(2);
} else {
this.value = value;
}
});
});
document.addEventListener('DOMContentLoaded', function () {
const radios = document.querySelectorAll('input[name="package_types"]');
const amountEl = document.getElementById('amountDisplay');
radios.forEach(radio => {
radio.addEventListener('click', function () {
const selected = this.value;
fetch(`/wp-admin/admin-ajax.php?action=get_package_price&type=${selected}`)
.then(res => res.json())
.then(data => {
if (data.success) {
amountEl.textContent = `$${parseFloat(data.data.amount).toFixed(2)}`;
} else {
console.warn('Failed to fetch price:', data.message);
}
})
.catch(err => {
console.error('AJAX error:', err);
});
});
});
});
document.getElementById('step2Form').addEventListener('submit', function (e) {
const cardNumber = document.getElementById('card_number').value.replace(/\s+/g, '');
const expiry = document.getElementById('expiry').value.trim();
const cvv = document.getElementById('cvv').value.trim();
// Card number Luhn check
if (!/^\d{13,19}$/.test(cardNumber) || !luhnCheck(cardNumber)) {
alert('Invalid card number.');
e.preventDefault();
return;
}
// Expiry format and date check
const [expMonth, expYear] = expiry.split('/');
const month = parseInt(expMonth, 10);
const year = parseInt('20' + expYear, 10);
const now = new Date();
const currentYear = now.getFullYear();
const currentMonth = now.getMonth() + 1;
if (
!/^\d{2}\/\d{2}$/.test(expiry) ||
month < 1 || month > 12 ||
year < currentYear ||
(year === currentYear && month < currentMonth)
) {
alert('Invalid or expired card date.');
e.preventDefault();
return;
}
// CVV check
if (!/^\d{3,4}$/.test(cvv)) {
alert('Invalid CVV.');
e.preventDefault();
return;
}
// All validations passed
console.log('Validation passed');
});
// Luhn algorithm
function luhnCheck(num) {
let sum = 0;
let shouldDouble = false;
for (let i = num.length - 1; i >= 0; i--) {
let digit = parseInt(num.charAt(i), 10);
if (shouldDouble) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
shouldDouble = !shouldDouble;
}
return (sum % 10) === 0;
}
jQuery(document).ready(function ($) {
// Define prices
const singlePrice = parseFloat($('#packageone').closest('label').nextAll('label').find('.price').first().text().replace('$', ''));
const familyPrice = parseFloat($('#packagetwo').closest('label').nextAll('label').find('.price').first().text().replace('$', ''));
const prices = {
single: singlePrice,
family: familyPrice
};
// Store package info when selected
$('input[name="radio-group"]').on('change', function () {
const selectedPackage = $(this).attr('id') === 'packageone' ? 'single' : 'family';
const selectedPrice = prices[selectedPackage];
// Update modal values
$('input[name="package_types"][value="' + selectedPackage + '"]').prop('checked', true);
$('#amountDisplay').text(`$${selectedPrice.toFixed(2)}`);
$('#amount').val(selectedPrice);
});
// Trigger the same logic on modal open to preserve selected value
// $('.rent-now-btn').on('click', function () {
// $('#modalStep1').modal('show');
// const selectedInput = $('input[name="radio-group"]:checked').attr('id');
// const selectedPackage = selectedInput === 'packageone' ? 'single' : 'family';
// const selectedPrice = prices[selectedPackage];
// $('input[name="package_types"][value="' + selectedPackage + '"]').prop('checked', true);
// $('#amountDisplay').text(`$${selectedPrice.toFixed(2)}`);
// $('#amount').val(selectedPrice);
// // Pass video ID
// const videoId = $(this).data('post-id');
// $('#rentalVideoId').val(videoId);
// });
});