'use strict'
var custom_url = location.href
var quickViewgalleryThumbs
var mobile_image_swiper
var quickViewgalleryTop
var is_rtl = $('#body').data('is-rtl')
var mode = is_rtl == 1 ? 'right' : 'left'
const is_loggedin = $('#is_loggedin').val()
var target_height = '';

var auth_settings = $('#auth_settings').val();

$.ajaxSetup({
    beforeSend: function (jqXHR, settings) {
        if (settings.type && settings.type.toUpperCase() === 'POST') {
            if (settings.data instanceof FormData) {
                settings.data.append(csrfName, csrfHash);
            } else if (typeof settings.data === 'string') {
                settings.data += (settings.data ? '&' : '') + encodeURIComponent(csrfName) + '=' + encodeURIComponent(csrfHash);
            } else {
                settings.data = settings.data || {};
                settings.data[csrfName] = csrfHash;
            }
        }
    }
});
function copyText() {
    /* Get the text to copy */
    const text = document.getElementById("#text-to-copy").innerText;

    /* Create a temporary input element */
    const tempInput = document.createElement("input");
    tempInput.type = "text";
    tempInput.value = text;
    document.body.appendChild(tempInput);

    /* Select and copy the text */
    tempInput.select();
    document.execCommand("copy");

    /* Remove the temporary input element */
    document.body.removeChild(tempInput);

    /* Update the copy button text */
    const copyButton = document.querySelector(".copy-button");
    copyButton.innerText = "Copied!";
    setTimeout(function () {
        copyButton.innerText = "Tap to copy";
    }, 1000);
}


//form-submit-event
window.Toast = Swal.mixin({
    toast: true,
    position: 'top-end',
    showConfirmButton: false,
    timer: 3000,
    timerProgressBar: true
})

function queryParams(p) {
    return {
        limit: p.limit,
        sort: p.sort,
        order: p.order,
        offset: p.offset,
        search: p.search
    }
}

// Password toggle functionality using jQuery event delegation
$(document).on('click', '.togglePassword', function () {
    // Try different methods to find the password input
    let input = $(this).prev()[0]; // Method 1: Direct sibling using jQuery

    // Method 2: If direct sibling doesn't work, look within the same input-group
    if (!input || (input.type !== 'password' && input.type !== 'text')) {
        const inputGroup = $(this).closest('.input-group');
        if (inputGroup.length) {
            input = inputGroup.find('input[type="password"], input[type="text"]')[0];
        }
    }

    // Method 3: Look in the same parent container
    if (!input || (input.type !== 'password' && input.type !== 'text')) {
        const parent = $(this).parent();
        input = parent.find('input[type="password"], input[type="text"]')[0];
    }

    // If we found a valid input, toggle it
    if (input && (input.type === 'password' || input.type === 'text')) {
        const icon = $(this).find('i'); // Get the eye icon
        if (input.type === 'password') {
            input.type = 'text';
            icon.removeClass('fa-eye').addClass('fa-eye-slash');
        } else {
            input.type = 'password';
            icon.removeClass('fa-eye-slash').addClass('fa-eye');
        }
    }
});

$(document).on('submit', '.form-submit-event', function (e) {

    e.preventDefault()

    // Remove name attribute from hidden form fields to prevent duplicate submissions
    var $form = $(this);
    var $hiddenInputs = $form.find('input[type="hidden"]');
    var $hiddenEmailForm = $form.find('#login-email-form');
    var $hiddenMobileForm = $form.find('#login-mobile-form');

    // If email form is hidden, remove name from its input
    if ($hiddenEmailForm.hasClass('d-none')) {
        $hiddenEmailForm.find('input[name="identity"]').removeAttr('name');
    }
    // If mobile form is hidden, remove name from its input
    if ($hiddenMobileForm.hasClass('d-none')) {
        $hiddenMobileForm.find('input[name="identity"]').removeAttr('name');
    }

    var formData = new FormData(this)
    var form_id = $(this).attr('id')
    var error_box = $('#error_box', this)
    var submit_btn = $(this).find('.submit_btn')
    var btn_html = $(this).find('.submit_btn').html()
    var btn_val = $(this).find('.submit_btn').val()
    var button_text =
        btn_html != '' || btn_html != 'undefined' ? btn_html : btn_val

    formData.append(csrfName, csrfHash)

    $.ajax({
        type: 'POST',
        url: $(this).attr('action'),
        data: formData,
        beforeSend: function () {
            submit_btn.html('Please Wait..');
            submit_btn.attr('disabled', true);
        },
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',

        success: function (result) {

            // Restore name attributes
          
            csrfName = result['csrfName'];
            csrfHash = result['csrfHash'];

            if (result['error'] == true) {

                error_box
                    .addClass('rounded p-3 alert alert-danger')
                    .removeClass('d-none alert-success');
                error_box.show().delay(5000).fadeOut();
                error_box.html(result['message']);

                submit_btn.html(button_text);
                submit_btn.attr('disabled', false);
                $('.form-submit-event')[0].reset();

                // 🔴 ERROR TOAST
                if (typeof Toast !== 'undefined' && Toast.fire) {
                    Toast.fire({
                        icon: 'error',
                        title: result['message']
                    });
                }

            } else {

                error_box
                    .addClass('rounded p-3 alert alert-success')
                    .removeClass('d-none alert-danger');
                error_box.show().delay(3000).fadeOut();
                error_box.html(result['message']);

                submit_btn.html(button_text);
                submit_btn.attr('disabled', false);
                $('.form-submit-event')[0].reset();

                // ✅ SUCCESS TOAST
                if (typeof Toast !== 'undefined' && Toast.fire) {
                    Toast.fire({
                        icon: 'success',
                        title: result['message']
                    });
                }

                if (form_id == 'login_form') {
                    var cart = localStorage.getItem('cart');
                    if (cart && cart !== null) {
                        cart_sync().then(function () {
                            setTimeout(function () {
                                window.location.reload();
                            }, 1000);
                        });
                    } else {
                        setTimeout(function () {
                            window.location.reload();
                        }, 1000);
                    }
                }
            }
        },


    });

})

// Email/Phone login toggle functionality for classic theme modals
$(document).on('click', '#login-canvas-emailLogin', function (e) {
    e.preventDefault();

    // Hide mobile form and show email form in login modal
    $('#login-mobile-form').addClass('d-none');
    $('#login-email-form').removeClass('d-none');

    // Remove required attribute from mobile input and add to email input
    $('#login-mobile-form input[name="identity"]').removeAttr('required');
    $('#login-email-form input[name="identity"]').attr('required', 'required');

    // Set the form to email login mode
    $('#login_form').attr('data-login-mode', 'email');

    // Toggle button visibility
    $('.emailLogin').addClass('d-none');
    $('.phoneLogin').removeClass('d-none');

    // Update validation rules for email
    $('#login_form').validate().destroy();
    $('#login_form').validate({
        ignore: ":hidden", // Ignore hidden form elements
        rules: {
            identity: {
                required: true,
                email: true
            }
        }
    });
});

// Handle phone login button click in modal
$(document).on('click', '#login_div #phoneLogin', function (e) {
    e.preventDefault();

    // Show mobile form and hide email form in login modal
    $('#login-mobile-form').removeClass('d-none');
    $('#login-email-form').addClass('d-none');

    // Remove required attribute from email input and add to mobile input
    $('#login-email-form input[name="identity"]').removeAttr('required');
    $('#login-mobile-form input[name="identity"]').attr('required', 'required');

    // Remove email login mode
    $('#login_form').removeAttr('data-login-mode');

    // Toggle button visibility
    $('.phoneLogin').addClass('d-none');
    $('.emailLogin').removeClass('d-none');

    // Update validation rules for mobile number
    $('#login_form').validate().destroy();
    $('#login_form').validate({
        ignore: ":hidden", // Ignore hidden form elements
        rules: {
            identity: {
                required: true,
                number: true,
                maxlength: 16
            }
        }
    });
});

// Handle email registration button click
$(document).on('click', '#register_div #emailLogin', function (e) {
    e.preventDefault();
    // Hide the email login link and show phone login link
    $('.email-login').addClass('d-none');
    $('.phone-login').removeClass('d-none');

    // Hide phone OTP forms and show email signup form
    $('#send-otp-form').hide();
    $('#verify-otp-form').hide();
    $('#sign-up-form').show().css('display', 'block');

    // Set the hidden type field to email for the signup form
    $('#sign-up-form').find('input[name="type"]').remove();
    $('#sign-up-form').append('<input type="hidden" name="type" value="email">');
});

// Handle phone registration button click
$(document).on('click', '#register_div #phoneLogin', function (e) {
    e.preventDefault();
    // Hide the phone login link and show email login link
    $('.phone-login').addClass('d-none');
    $('.email-login').removeClass('d-none');

    // Show phone OTP send form and hide email signup form
    $('#send-otp-form').show();
    $('#verify-otp-form').hide();
    $('#sign-up-form').hide();

    // Remove email type field if it exists
    $('#sign-up-form').find('input[name="type"][value="email"]').remove();
});

if (auth_settings == "firebase") {

    /**
     * Function called when clicking the Login/Logout button.
     */
    function onSignInSubmit(e) {
        e.preventDefault()
        if (isPhoneNumberValid()) {
            $('#send-otp-button').html('Please Wait...')
            var response = is_user_exist()
            updateSignInButtonUI()
            if (response.error == true) {
                $('#is-user-exist-error').html(response.message)
                $('#send-otp-button').html('Send OTP')
            } else {
                window.signingIn = true

                var phoneNumber = getPhoneNumberFromUserInput()
                var appVerifier = window.recaptchaVerifier
                firebase
                    .auth()
                    .signInWithPhoneNumber(phoneNumber, appVerifier)
                    .then(function (confirmationResult) {
                        $('#send-otp-button').html('Send OTP')
                        $('.send-otp-form').unblock()
                        window.signingIn = false
                        updateSignInButtonUI()
                        resetRecaptcha()
                        $('#send-otp-form').hide()
                        $('#otp_div').show()
                        $('#verify-otp-form').removeClass('d-none')
                        $(document).on('submit', '#verify-otp-form', function (e) {
                            e.preventDefault()
                            $('#registration-error').html('')
                            var code = $('#otp').val()
                            var formdata = new FormData(this)
                            var url = $(this).attr('action')
                            $('#register_submit_btn')
                                .html('Please Wait...')
                                .attr('disabled', true)
                            confirmationResult
                                .confirm(code)
                                .then(function (result) {
                                    formdata.append(csrfName, csrfHash)
                                    formdata.append('mobile', $('#phone-number').val())
                                    formdata.append('country_code', $('.selected-dial-code').text())
                                    $.ajax({
                                        type: 'POST',
                                        url: url,
                                        data: formdata,
                                        processData: false,
                                        contentType: false,
                                        cache: false,
                                        dataType: 'json',
                                        beforeSend: function () {
                                            $('#register_submit_btn')
                                                .html('Please Wait...')
                                                .attr('disabled', true)
                                        },
                                        success: function (result) {
                                            csrfName = result.csrfName
                                            csrfHash = result.csrfHash
                                            $('#register_submit_btn')
                                                .html('Submit')
                                                .attr('disabled', false)
                                            $('#registration-error').html(result.message).show()
                                        }
                                    })
                                })
                                .catch(function (error) {
                                    $('#register_submit_btn')
                                        .html('Please Wait...')
                                        .attr('disabled', true)
                                    $('#registration-error')
                                        .html('Invalid OTP. Please Enter Valid OTP')
                                        .show()
                                })
                        })
                    })
                    .catch(function (error) {
                        window.signingIn = false
                        $('#is-user-exist-error').html(error.message).show()
                        $('#send-otp-button').html('Send OTP')
                        updateSignInButtonUI()
                        resetRecaptcha()
                    })
            }
        }
    }
    /**
     * Set up UI event listeners and registering Firebase auth listeners.
     */
    // Use jQuery event delegation for form submission to work with dynamically added elements
    $(document).on('submit', '#send-otp-form', onSignInSubmit);

    // Phone number input listeners with event delegation
    $(document).on('keyup', '#phone-number', updateSignInButtonUI);
    $(document).on('change', '#phone-number', updateSignInButtonUI);

    window.onload = function () {
        var offerPopupValue = document.getElementById("offer_popup_value");
        if (offerPopupValue && (offerPopupValue.value == "refresh" || offerPopupValue.value == "session_storage")) {
            $("#offer_popup").modal("show");
        }
    }

    /**
     * Reads the phone number from the user input.
     */
    function getPhoneNumberFromUserInput() {
        var countrycode = $('.selected-dial-code').html()
        var phonenumber = $('#phone-number').val()
        return countrycode + phonenumber
    }

    /**
     * Returns true if the phone number is valid.
     */
    function isPhoneNumberValid() {
        var pattern = /^\+[0-9\s\-\(\)]+$/
        var phoneNumber = getPhoneNumberFromUserInput()
        return phoneNumber.search(pattern) !== -1
    }

    /**
     * This resets the recaptcha widget.
     */
    function resetRecaptcha() {
        return window.recaptchaVerifier.render().then(function (widgetId) {
            grecaptcha.reset(widgetId)
        })
    }
}

if (auth_settings == "sms") {


    $(document).on("click", "#send-otp-button", function (e) {
        e.preventDefault();
        var t = $("#phone-number").val();
        $.ajax({
            type: "POST",
            async: !1,
            url: base_url + "auth/verify_user",
            data: {
                mobile: t,
                [csrfName]: csrfHash
            },
            dataType: "json",
            success: function (e) {
                csrfName = e.csrfName,
                    csrfHash = e.csrfHash;
                if (e.error == true) {
                    $("#registration-user-error").html(e.message).show();
                } else {
                    $("#send-otp-form").hide(),
                        $("#verify-otp-form").removeClass("d-none");
                }
            }
        })
    });

    $(document).on('submit', '#verify-otp-form', function (e) {
        e.preventDefault()
        $('#registration-error').html('')
        var code = $('#otp').val()
        var formdata = new FormData(this)
        var url = $(this).attr('action')
        $('#register_submit_btn')
            .html('Please Wait...')
        formdata.append(csrfName, csrfHash)
        formdata.append('mobile', $('#phone-number').val())
        formdata.append('country_code', $('.selected-dial-code').text())
        $.ajax({
            type: 'POST',
            url: url,
            data: formdata,
            processData: false,
            contentType: false,
            cache: false,
            dataType: 'json',
            beforeSend: function () {
                $('#register_submit_btn')
                    .html('<div class="spinner-border" role="status">' +
                        '<span class="visually-hidden">Loading...</span>' +
                        '</div>').attr('disabled', true);
            },
            success: function (result) {
                csrfName = result.csrfName
                csrfHash = result.csrfHash
                $('#register_submit_btn')
                    .html('Submit')
                $('#registration-error').html(result.message).show()
                if (result.error == false) {
                    $('.registration-section').hide()
                    $('.login-section').show()
                }
            }
        })
    })

    $(document).on("click", "#forgot_password_send_otp_btn", function (e) {
        e.preventDefault();
        var t = $("#forgot_password_number").val();
        var forget_password_val = $('#forget_password_val').val();

        $.ajax({
            type: "POST",
            async: !1,
            url: base_url + "auth/verify_user",
            data: {
                mobile: t,
                forget_password_val: forget_password_val,
                [csrfName]: csrfHash
            },
            dataType: "json",
            success: function (e) {
                csrfName = e.csrfName,
                    csrfHash = e.csrfHash,
                    $("#send_forgot_password_otp_form").hide(),
                    $("#otp_div").show(),
                    $("#verify_forgot_password_otp_form").removeClass("d-none");
            }
        })
    });

    $(document).on('submit', '#verify_forgot_password_otp_form', function (e) {
        e.preventDefault()
        var reset_pass_btn_html = $('#reset_password_submit_btn').html()
        var code = $('#forgot_password_otp').val()
        var formdata = new FormData(this)
        var url = base_url + 'home/reset-password'
        $('#reset_password_submit_btn')
            .html('Please Wait...')
            .attr('disabled', true)
        formdata.append(csrfName, csrfHash)
        formdata.append('mobile', $('#forgot_password_number').val())
        $.ajax({
            type: 'POST',
            url: url,
            data: formdata,
            processData: false,
            contentType: false,
            cache: false,
            dataType: 'json',
            beforeSend: function () {
                $('#reset_password_submit_btn')
                    .html('Please Wait...')
                    .attr('disabled', true)
            },
            success: function (result) {
                csrfName = result.csrfName
                csrfHash = result.csrfHash
                $('#reset_password_submit_btn')
                    .html(reset_pass_btn_html)
                    .attr('disabled', false)
                $('#set_password_error_box').html(result.message).show()
                if (result.error == false) {
                    setTimeout(function () {
                        window.location.reload()
                    }, 2000)
                }
            }
        })
    })

}

function resetRecaptcha() {
    return window.recaptchaVerifier.render().then(function (e) {
        grecaptcha.reset(e)
    })
}


$(document).on('click', '#resend-otp', function (e) {

    e.preventDefault()
})

/**
 * Updates the Sign-in button state depending on ReCaptcha and form values state.
 */
function updateSignInButtonUI() { }

function is_user_exist(phone_number = '') {
    if (phone_number == '') {
        var phoneNumber = $('#phone-number').val()
    } else {
        var phoneNumber = phone_number
    }
    var response
    $.ajax({
        type: 'POST',
        async: false,
        url: base_url + 'auth/verify_user',
        data: {
            mobile: phoneNumber,
            [csrfName]: csrfHash
        },
        dataType: 'json',
        success: function (result) {
            csrfName = result['csrfName']
            csrfHash = result['csrfHash']
            response = result
        }
    })
    return response
}

$(document).on('submit', '.sign-up-form', function (e) {
    e.preventDefault()

    // Check if this is phone registration (has phone-number field) or email registration
    var isPhoneRegistration = $('#phone-number').length > 0 && $('#phone-number').is(':visible');
    var registrationType = $(this).find('input[name="type"]').val();

    // If this is email registration, let the ID-based handler (#sign-up-form) handle it
    if (registrationType === 'email' || !isPhoneRegistration) {
        return;
    }

    var countrycode = $('.selected-dial-code').html()
    var $phonenumber = $('#phone-number').val()
    var $username = $('input[name="username"]').val()
    var $email = $('input[name="email"]').val()
    var $passwd = $('input[name="password"]').val()

    // Only proceed if we have a valid phone number
    if (!$phonenumber) {
        return;
    }

    $.ajax({
        type: 'POST',
        url: base_url + 'auth/register_user',
        data: {
            country_code: countrycode,
            mobile: $phonenumber,
            name: $username,
            email: $email,
            password: $passwd,
            [csrfName]: csrfHash
        },
        dataType: 'json',
        success: function (result) {
            if (result.error == true) {
                $('#sign-up-error').html(
                    '<span class="text-danger" >' + response.message + '</span>'
                )
            }
        }
    })
})

// Handle email signup form submission for classic theme
$(document).on('submit', '#sign-up-form', function (e) {
    e.preventDefault();

    var email = $(this).find('input[name="email"]').val();
    var password = $(this).find('input[name="password"]').val();
    var username = $(this).find('input[name="username"]').val();
    var type = 'email';
    var web_fcm = $('#web_fcm').val() || '';

    $.ajax({
        type: 'POST',
        url: base_url + 'home/verifyUser',
        data: {
            email: email,
            type: type,
            [csrfName]: csrfHash
        },
        dataType: 'json',
        success: function (result) {
            csrfName = result.csrfName;
            csrfHash = result.csrfHash;

            if (result.error == true) {
                // Create the user in Firebase
                firebase.auth().createUserWithEmailAndPassword(email, password)
                    .then(function (userCredential) {
                        userCredential.user.sendEmailVerification().then(() => {
                            
                            Swal.fire({
                                title: 'Verification Email Sent',
                                text: 'Please check your email to verify your account before logging in.',
                                icon: 'info',
                            });
                        });
                        setTimeout(function () {
                            userCredential.user.updateProfile({
                                displayName: username
                            });
                        }, 2000);
                    }).then(function () {
                        var formData = {
                            name: username,
                            email: email,
                            password: password,
                            type: type,
                            web_fcm: web_fcm,
                            [csrfName]: csrfHash
                        };

                        $.ajax({
                            type: 'POST',
                            url: base_url + 'auth/register_user',
                            data: formData,
                            dataType: 'json',
                            success: function (result) {
                                csrfName = result['csrfName'];
                                csrfHash = result['csrfHash'];
                                Toast.fire({
                                    icon: 'success',
                                    title: 'Registration successful! Please verify your email before logging in.'
                                });

                                if (result.error == false) {
                                    // Don't auto-login - user must verify email first
                                    Swal.fire({
                                        title: 'Registration Complete',
                                        text: 'Your account has been created successfully. Please check your email and verify your account before logging in.',
                                        icon: 'success',
                                        confirmButtonText: 'OK'
                                    });
                                } else {
                                    $('#sign-up-error').html('<div class="alert alert-danger">' + result.message + '</div>');
                                }
                            }
                        });
                    })
                    .catch(function (error) {
                        console.error('Error:', error);
                        $('#sign-up-error').html('<div class="alert alert-danger">Registration failed: ' + error.message + '</div>');
                    });
            } else {
                $('#sign-up-error').html('<div class="alert alert-danger">' + result.message + '</div>');
            }
        }
    });
});

function formatRepo(repo) {
    if (repo.loading) return repo.text
    var markup =
        "<div class='select2-result-repository clearfix'>" +
        "<div class='select2-result-repository__avatar'><img src='" +
        repo.image_sm +
        "' /></div>" +
        "<div class='select2-result-repository__meta'>" +
        "<div class='select2-result-repository__title'>" +
        repo.name +
        '</div>'

    if (repo.category_name) {
        markup +=
            "<div class='select2-result-repository__description'> In " +
            repo.category_name +
            '</div>'
    }

    return markup
}

function formatRepoSelection(repo) {
    return repo.name || repo.text
}

var search_products = $('.search_product').select2({
    ajax: {
        url: base_url + 'home/get_products',
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                search: params.term, // search term
                page: params.page
            }
        },
        processResults: function (response, params) {
            // parse the results into the format expected by Select2
            // since we are using custom formatting functions we do not need to
            // alter the remote JSON data, except to indicate that infinite
            // scrolling can be used
            params.page = params.page || 1

            return {
                results: response.data,
                pagination: {
                    more: params.page * 30 < response.total
                }
            }
        },
        cache: true
    },
    escapeMarkup: function (markup) {
        return markup
    },
    minimumInputLength: 1,
    templateResult: formatRepo,
    templateSelection: formatRepoSelection,
    theme: 'adwitt',
    placeholder: 'Search for products'
})

search_products.on('select2:select', function (e) {
    var data = e.params.data
    if (data.link != undefined && data.link != null) {
        window.location.href = data.link
    }
})

$('#leftside-navigation .sub-menu > a').click(function (e) {
    $('#leftside-navigation ul ul').slideUp()

    !$('#leftside-navigation .sub-menu > a').next().is(':visible') ?
        $('#leftside-navigation .sub-menu > a')
            .find('.arrow')
            .removeClass('fa-angle-down')
            .addClass('fa-angle-left') :
        ''
    $(this).find('.arrow').hasClass('fa-angle-left') ?
        $(this)
            .find('.arrow')
            .removeClass('fa-angle-left')
            .addClass('fa-angle-down') :
        $(this)
            .find('.arrow')
            .removeClass('fa-angle-down')
            .addClass('fa-angle-left')
    $(this).next().is(':visible') || $(this).next().slideDown()
    e.stopPropagation()
})

$('li.has-ul').click(function () {
    $(this).children('.sub-ul').slideToggle(500)
    $(this).toggleClass('active')
    event.preventDefault()
})

$('.add-to-fav-btn').on('click', function (e) {
    e.preventDefault();

    var formdata = new FormData();
    var product_id = $(this).data('product-id');
    var fav_btn = $(this);

    formdata.append(csrfName, csrfHash);
    formdata.append('product_id', product_id);

    $.ajax({
        type: 'POST',
        url: base_url + 'my-account/manage-favorites',
        data: formdata,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (result) {

            csrfName = result.csrfName;
            csrfHash = result.csrfHash;

            // Toggle icon
            if (!result.error) {
                if (fav_btn.hasClass('far')) {
                    fav_btn.removeClass('far').addClass('fa text-danger');
                } else {
                    fav_btn.removeClass('fa text-danger').addClass('far');
                }
            }

            // Toast for 3 seconds
            Toast.fire({
                icon: result.error ? 'error' : 'success',
                title: result.message,
                timer: 3000,
                timerProgressBar: true
            });

            // Reload after toast ends
            setTimeout(function () {
                location.reload();
            }, 3000);
        }
    });
});

$(document).on('click', '#add_to_favorite_btn', function (e) {
    e.preventDefault()
    var formdata = new FormData()
    var product_id = $(this).data('product-id')
    var fav_btn = $(this)
    var fav_btn_html = $(this).html()
    formdata.append(csrfName, csrfHash)
    formdata.append('product_id', product_id)
    $.ajax({
        type: 'POST',
        url: base_url + 'my-account/manage-favorites',
        data: formdata,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        beforeSend: function () {
            fav_btn.attr('disabled', true)
            fav_btn.find('span').text('Please wait')
        },
        success: function (result) {
            csrfName = result.csrfName
            csrfHash = result.csrfHash
            fav_btn.attr('disabled', false)
            fav_btn.html(fav_btn_html)
            if (result.error == true) {
                Toast.fire({
                    icon: 'error',
                    title: result.message
                })
            } else {
                if (fav_btn.hasClass('add-fav')) {
                    fav_btn.removeClass('add-fav').addClass('remove-fav')
                    fav_btn.find('span').text('Remove from Favorite')
                } else {
                    fav_btn.removeClass('remove-fav').addClass('add-fav')
                    fav_btn.find('span').text('Add to Favorite')
                }
            }
        }
    })
})


var swiper2 = new Swiper(".swiperForBrands", {
    slidesPerView: 1,
    spaceBetween: 10,
    navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
    },
    breakpoints: {
        640: {
            slidesPerView: 3,
            spaceBetween: 10,
        },
        768: {
            slidesPerView: 4,
            spaceBetween: 10,
        },
        991: {
            slidesPerView: 5,
            spaceBetween: 10,
        },
        1024: {
            slidesPerView: 6,
            spaceBetween: 10,
        },
        1440: {
            slidesPerView: 8,
            spaceBetween: 10,
        },
    },
});

$(function () {
    /* Instantiating iziModal */
    $('.auth-modal').iziModal({
        overlayClose: false,
        overlayColor: 'rgba(0, 0, 0, 0.6)'
    })

    if ($('#user-review-images').length) {
        var review_title = ''
        review_title = $('#review-image-title').data('review-title')
        var id = $('#review-image-title').data('product-id')
        var u = 0
        var d = 0
        var image_data = ''
        $('#user-review-images').iziModal({
            overlayClose: false,
            overlayColor: 'rgba(0, 0, 0, 0.6)',
            title: review_title,
            headerColor: '#f44336c4',
            arrowKeys: false,
            fullscreen: true,
            onOpening: function (modal) {
                modal.startLoading()
                var limit = $('#review-image-title').data('review-limit')
                var offset = $('#review-image-title').data('review-offset')
                var reached_end = $('#review-image-title').data('reached-end')
                $('#load_more_div').html('<div id="load_more"></div>')
                if (reached_end == false) {
                    load_review_images(id, limit, offset)
                }

                modal.stopLoading()
            },
            onOpened: function () {
                $('div').bind('wheel', function (e) {

                    if ($('#load_more').length) {
                        if (
                            $(this).scrollTop() + $(this).innerHeight() >=
                            $(this)[0].scrollHeight
                        ) {
                            var id = $('#review-image-title').data('product-id')
                            var limit = $('#review-image-title').data('review-limit')
                            var offset = $('#review-image-title').data('review-offset')
                            var reached_end = $('#review-image-title').data('reached-end')
                            if (reached_end == false) {
                                load_review_images(id, limit, offset)
                            }
                        }
                    }
                })
            }
        })
    }

    function load_review_images(
        product_id,
        limit,
        offset,
        target = '#user_image_data'
    ) {
        $('#review-image-title').data('review-offset', offset + limit)
        $.getJSON(
            base_url +
            'products/get_rating?product_id=' +
            product_id +
            '&has_images=1&limit=' +
            limit +
            '&offset=' +
            offset,
            function (data) {
                $('#review-image-title').data('review-offset', offset + limit)
                image_data = ''
                var obj = 0
                if (data.error == false) {
                    for (var i = 0; i < data.data.product_rating.length; i++) {
                        obj = data.data.product_rating[i]
                        for (var j = 0; j < obj.images.length; j++) {
                            var obj3 = obj.images
                            image_data +=
                                "<div class='review-box '><a href='" +
                                obj3[j] +
                                "' data-lightbox='review-images-12345' data-title='<font >" +
                                obj.rating +
                                ' &#9733;</font></br>' +
                                obj.user_name +
                                '<br>' +
                                obj.comment +
                                "'><img src='" +
                                obj3[j] +
                                "' alt='Review Image'></a></div>"
                        }
                    }
                } else {
                    $('#review-image-title').data('reached-end', 'true')
                }
                $(target).append(image_data)
            }
        )
    }


    $(document).on("change", ".brand", function (e) {
        e.preventDefault();
        var t = $(this).data("value");
        custom_url = setUrlParameter(custom_url, "brand", t);

        const brand_name = getUrlParameter('brand');
        var brands = $('[data-value="' + brand_name + '"]');
        $('[data-value="' + brand_name + '"]').attr('checked', true);
        var gp = $(brands).siblings();
        $(gp).removeClass('selected-brand');
    }),


        $('#quick-view').iziModal({
            overlayClose: false,
            overlayColor: 'rgba(0, 0, 0, 0.6)',
            width: 1000,
            onOpening: function (modal) {
                modal.startLoading()
                $('#modal-product-tags').html('')
                $.getJSON(
                    base_url +
                    'products/get-details/' +
                    modal.$element.data('dataProductId'),
                    function (data) {
                        var total_images = 0
                        $('#modal-add-to-cart-button').attr('data-product-id', data.id)

                        $('#modal-add-to-cart-button').attr(
                            'data-product-variant-id',
                            data.variants[0].id
                        )
                        if (
                            data.minimum_order_quantity != 1 &&
                            data.minimum_order_quantity != '' &&
                            data.minimum_order_quantity != 'undefined'
                        ) {
                            $('.in-num').attr({
                                'data-min': data.minimum_order_quantity // values (or variables) here
                            })
                            $('.minus').attr({
                                'data-min': data.minimum_order_quantity // values (or variables) here
                            })
                            $('#modal-add-to-cart-button').attr({
                                'data-min': data.minimum_order_quantity // values (or variables) here
                            })
                        } else {
                            $('.in-num').attr({
                                'data-min': 1 // values (or variables) here
                            })
                            $('.minus').attr({
                                'data-min': 1 // values (or variables) here
                            })
                            $('#modal-add-to-cart-button').attr({
                                'data-min': 1 // values (or variables) here
                            })
                        }
                        if (
                            data.quantity_step_size != 1 &&
                            data.quantity_step_size != '' &&
                            data.quantity_step_size != 'undefined'
                        ) {
                            $('.in-num').attr({
                                'data-step': data.quantity_step_size // values (or variables) here
                            })
                            $('.minus').attr({
                                'data-step': data.quantity_step_size // values (or variables) here
                            })
                            $('.plus').attr({
                                'data-step': data.quantity_step_size // values (or variables) here
                            })
                            $('#modal-add-to-cart-button').attr({
                                'data-step': data.quantity_step_size // values (or variables) here
                            })
                        } else {
                            $('.in-num').attr({
                                'data-step': 1 // values (or variables) here
                            })
                            $('.minus').attr({
                                'data-step': 1 // values (or variables) here
                            })
                            $('.plus').attr({
                                'data-step': 1 // values (or variables) here
                            })
                            $('#modal-add-to-cart-button').attr({
                                'data-step': 1 // values (or variables) here
                            })
                        }
                        if (
                            data.total_allowed_quantity != '' &&
                            data.total_allowed_quantity != 'undefined' &&
                            data.total_allowed_quantity != null
                        ) {
                            $('.in-num').attr({
                                'data-max': data.total_allowed_quantity // values (or variables) here
                            })
                            $('.plus').attr({
                                'data-max': data.total_allowed_quantity // values (or variables) here
                            })
                            $('#modal-add-to-cart-button').attr({
                                'data-max': data.total_allowed_quantity // values (or variables) here
                            })
                        } else {
                            $('.in-num').attr({
                                'data-max': 1 // values (or variables) here
                            })
                            $('.plus').attr({
                                'data-max': 1 // values (or variables) here
                            })
                            $('#modal-add-to-cart-button').attr({
                                'data-max': 1 // values (or variables) here
                            })
                        }
                        $('#modal-product-quantity').val(data.minimum_order_quantity)
                        $('#modal-product-title').text(data.name)
                        if (data.brand && data.brand !== '' && data.brand !== null) {
                            let brand = '<a href="' + base_url + "products?brand=" + data.brand_slug + '">' + data.brand + '</a>'
                            $('#modal-product-brand').html(brand);
                            $('.quickview-product-brands').removeClass('d-none');
                        } else {
                            $('.quickview-product-brands').addClass('d-none');
                        }
                        $('#modal-product-short-description').text(data.short_description)
                        $('#modal-product-rating').rating('update', data.rating)
                        var price = data.get_price.range
                        $('#modal-product-price').html(price)

                        let whatsappNumber = $('#whatsappNumber').val();
                        $('#whatsappButton').on('click', function () {
                            var whatsappLink = 'https://api.whatsapp.com/send?phone=' + whatsappNumber + '&text=Hello, I Seen ' + data.name + ' In Your Website And I Want to Buy This'
                            window.open(whatsappLink, '_blank');
                        })
                        //Quick View Product Modal Gallery Swiper
                        quickViewgalleryThumbs = new Swiper('.gallery-thumbs', {
                            spaceBetween: 10,
                            slidesPerView: 4,
                            freeMode: true,
                            watchSlidesVisibility: true,
                            watchSlidesProgress: true
                        })
                        quickViewgalleryTop = new Swiper('.gallery-top', {
                            spaceBetween: 10,
                            navigation: {
                                nextEl: '.swiper-button-next',
                                prevEl: '.swiper-button-prev'
                            },
                            thumbs: {
                                swiper: quickViewgalleryThumbs
                            },
                            clickable: true
                        })

                        //preview-image-swiper
                        mobile_image_swiper = new Swiper('.mobile-image-swiper', {
                            pagination: {
                                el: '.mobile-image-swiper-pagination'
                            },
                            clickable: true
                        })

                        quickViewgalleryThumbs.removeAllSlides()
                        quickViewgalleryTop.removeAllSlides()
                        mobile_image_swiper.removeAllSlides()
                        var thumb_images =
                            '<div class="swiper-slide text-center">' +
                            '<div class="product-view-grid">' +
                            '<div class="product-view-image">' +
                            '<div class="product-view-image-container">' +
                            '<img src="' +
                            data.image_md +
                            '" data-zoom-image="">' +
                            '</div></div></div></div>'
                        var main_images =
                            '<div class="swiper-slide text-center">' +
                            '<div class="product-view-grid">' +
                            '<div class="product-view-image">' +
                            '<div class="product-view-image-container">' +
                            '<img src="' +
                            data.image_md +
                            '">' +
                            '</div></div></div></div>'
                        var mobile_slider_image =
                            '<div class="swiper-slide text-center"><img src="' +
                            data.image_md +
                            '"></div>'
                        var variant_images_md = data.variants.map(function (value, index) {
                            return value.images_md
                        })

                        $.each(variant_images_md, function (i, images) {
                            if (images != null && images != '') {
                                $.each(images, function (i, url) {
                                    thumb_images +=
                                        '<div class="swiper-slide text-center">' +
                                        '<div class="product-view-grid">' +
                                        '<div class="product-view-image">' +
                                        '<div class="product-view-image-container">' +
                                        '<img src="' +
                                        url +
                                        '" data-zoom-image="">' +
                                        '</div></div></div></div>'

                                    main_images +=
                                        '<div class="swiper-slide text-center">' +
                                        '<div class="product-view-grid">' +
                                        '<div class="product-view-image">' +
                                        '<div class="product-view-image-container">' +
                                        '<img src="' +
                                        url +
                                        '">' +
                                        '</div></div></div></div>'

                                    mobile_slider_image +=
                                        '<div class="swiper-slide text-center"><img src="' +
                                        url +
                                        '"></div>'
                                })
                            }
                        })
                        $.each(data.other_images_md, function (i, url) {
                            total_images++
                            thumb_images +=
                                '<div class="swiper-slide text-center">' +
                                '<div class="product-view-grid">' +
                                '<div class="product-view-image">' +
                                '<div class="product-view-image-container">' +
                                '<img src="' +
                                url +
                                '" data-zoom-image="">' +
                                '</div></div></div></div>'

                            main_images +=
                                '<div class="swiper-slide text-center">' +
                                '<div class="product-view-grid">' +
                                '<div class="product-view-image">' +
                                '<div class="product-view-image-container">' +
                                '<img src="' +
                                url +
                                '">' +
                                '</div></div></div></div>'

                            mobile_slider_image +=
                                '<div class="swiper-slide text-center"><img src="' +
                                url +
                                '"></div>'
                        })

                        quickViewgalleryThumbs.addSlide(1, thumb_images)
                        quickViewgalleryTop.addSlide(1, main_images)
                        mobile_image_swiper.addSlide(1, mobile_slider_image)
                        var variant_attributes = ''
                        var is_image = 0
                        var is_color = 0
                        $.each(data.variant_attributes, function (i, e) {
                            var attribute_ids = e.ids.split(',')
                            var attribute_values = e.values.split(',')
                            var swatche_types = e.swatche_type.split(',')
                            var swatche_values = e.swatche_value.split(',')
                            var style =
                                '<style> .product-page-details .btn-group>.active { border: 1px solid black;}</style>'
                            variant_attributes +=
                                '<h4>' +
                                e.attr_name +
                                '</h4><div class="btn-group btn-group-toggle" data-toggle="buttons">'
                            $.each(attribute_ids, function (j, id) {
                                var isFirst = (j === 0)
                                var activeClass = isFirst ? ' active' : ''
                                var checkedAttr = isFirst ? ' checked' : ''
                                var color_code = ''
                                if (swatche_types[j] == '1') {
                                    is_color = 1
                                    color_code =
                                        'style="background-color:' + swatche_values[j] + '";'
                                    variant_attributes +=
                                        '<style> .product-page-details .btn-group>.active { border: 1px solid black;}</style>' +
                                        '<button class="btn fullCircle' + activeClass + '" ' +
                                        color_code +
                                        '>' +
                                        '<input type="radio" name="' +
                                        e.attr_name +
                                        '" value="' +
                                        id +
                                        '" class="modal-product-attributes" autocomplete="off"' + checkedAttr + '><br>' +
                                        '</button>'
                                } else if (swatche_types[j] == '2') {
                                    is_image = 1
                                    variant_attributes +=
                                        '<style> .product-page-details .btn-group>.active { color: #000000; border: 1px solid black;}</style>' +
                                        '<label class="btn text-center bg-transparent' + activeClass + '">' +
                                        '<img class="swatche-image" src="' +
                                        swatche_values[j] +
                                        '">' +
                                        '<input type="radio" name="' +
                                        e.attr_name +
                                        '" value="' +
                                        id +
                                        '" class="modal-product-attributes" autocomplete="off"' + checkedAttr + '><br>' +
                                        '</label>'
                                } else {
                                    var style1 =
                                        '<style> .product-page-details .btn-group>.active { background-color: var(--primary-color);color: white!important;}</style>'
                                    variant_attributes +=
                                        style1 +
                                        '<label class="btn btn-default text-center' + activeClass + '">' +
                                        '<input type="radio" name="' +
                                        e.attr_name +
                                        '" value="' +
                                        id +
                                        '" class="modal-product-attributes" autocomplete="off"' + checkedAttr + '>' +
                                        attribute_values[j] +
                                        '<br>' +
                                        '</label>'
                                }
                            })
                            variant_attributes += '</div>'
                        })
                        var className = data.is_deliverable == false ? 'danger' : 'success'
                        var is_not = data.is_deliverable == false ? 'not' : ''
                        var err_msg =
                            data.zipcode != '' && typeof data.zipcode !== 'undefined' ?
                                '<b class="text-' +
                                className +
                                '">Product is ' +
                                is_not +
                                ' delivarable on &quot; ' +
                                data.zipcode +
                                ' &quot; </b>' :
                                ''
                        variant_attributes +=
                            '<form class="mt-2 validate_zipcode_quick_view"   method="post" >' +
                            '<div class="d-flex">' +
                            '<div class=" col-md-6 pl-0">' +
                            '<input type="hidden" name="product_id" value="' +
                            data.id +
                            '">' +
                            '<input type="hidden" name="' +
                            csrfName +
                            '" value="' +
                            csrfHash +
                            '">' +
                            '<input type="text" class="form-control" id="zipcode" placeholder="Zipcode" name="zipcode" required value="' +
                            data.zipcode +
                            '">' +
                            '</div>' +
                            '<button type="submit" class="button button-primary-outline m-0" data-product_id="' +
                            data.id +
                            '"  data-zipcode="' +
                            data.zipcode +
                            '"  id="validate_zipcode">Check Availability</button>' +
                            '</div>' +
                            '<div class="mt-2" id="error_box1">' +
                            err_msg +
                            ' </div>' +
                            ' </form>'
                        $('#modal-product-variant-attributes').html(variant_attributes)
                        if (
                            data.is_deliverable == false &&
                            data.zipcode != '' &&
                            typeof data.zipcode !== 'undefined'
                        ) {
                            $('#modal-add-to-cart-button').attr('disabled', 'true')
                        } else {
                            $('#modal-add-to-cart-button').removeAttr('disabled')
                        }
                        var variants = ''
                        total_images = 1
                        $.each(data.variants, function (i, e) {
                            variants +=
                                '<input type="hidden" class="modal-product-variants" data-image-index="' +
                                total_images +
                                '" name="variants_ids" data-name="' +
                                data.name +
                                '" value="' +
                                e.variant_ids +
                                '" data-id="' +
                                e.id +
                                '" data-price="' +
                                e.price +
                                '" data-special_price="' +
                                e.special_price +
                                '" data-variant-values="' +
                                (e.variant_values || '') +
                                '">'
                            total_images += e.images.length
                        })
                        $('#modal-product-variants-div').html(variants)
                        $('#add_to_favorite_btn').attr('data-product-id', data.id)
                        if (data.is_favorite == 1) {
                            $('#add_to_favorite_btn').addClass('remove-fav')
                            $('#add_to_favorite_btn').find('span').text('Remove From Favorite')
                        } else {
                            $('#add_to_favorite_btn').addClass('add-fav')
                            $('#add_to_favorite_btn').find('span').text('Add to Favorite')
                        }
                        $('#compare').attr('data-product-id', data.id)
                        if (data.type == 'simple_product') {
                            $('#compare').attr('data-product-variant-id', data.variants[0].id)
                        } else {
                            $('#compare').attr('data-product-variant-id', '')
                        }
                        var compare = ''
                        $.each(data, function (i, e) {
                            compare +=
                                '<button type="button" name="compare" class="buttons btn-6-6 extra-small m-0 compare" id="compare" data-product-id="' +
                                data.id +
                                '" data-product-variant-id="' +
                                data.variants.id +
                                '"><i class="fa fa-random"></i> Compare</button>'
                        })
                        $('#modal-product-no-of-ratings').text(data.no_of_ratings)
                        if (!$.isEmptyObject(data.tags)) {
                            var tags = 'Tags '
                            $.each(data.tags, function (i, e) {
                                tags +=
                                    '<a href="' +
                                    base_url +
                                    'products/tags/' +
                                    e +
                                    '" target="_blank"><span class="badge bg-secondary p-1 mr-1">' +
                                    e +
                                    '</span></a>'
                            })
                            $('#modal-product-tags').html(tags)
                        }

                        modal.stopLoading()

                        setTimeout(function () {
                            $('.modal-product-attributes:checked:first').trigger('change')
                        }, 100)
                    }
                )
            }
        })

    //Modal Product Variant Selection Event
    $(document).on('change', '.modal-product-attributes', function (e) {
        e.preventDefault()
        var selected_attributes = []
        var attributes_length = ''
        var price = ''
        var is_variant_available = false
        var variant = []
        var prices = []
        var variant_prices = []
        var variants = []
        var variant_ids = []
        var image_indexes = []
        var selected_image_index
        $('.modal-product-variants').each(function () {
            prices = {
                price: $(this).data('price'),
                special_price: $(this).data('special_price')
            }
            variant_ids.push($(this).data('id'))
            variant_prices.push(prices)
            variant = $(this).val().split(',')
            variants.push(variant)
            image_indexes.push($(this).data('image-index'))
        })
        attributes_length = variant.length
        $('.modal-product-attributes').each(function () {
            if ($(this).prop('checked')) {
                selected_attributes.push($(this).val())

                if (selected_attributes.length == attributes_length) {
                    /* compare the arrays */
                    prices = []
                    var selected_variant_id = ''
                    $.each(variants, function (i, e) {
                        if (arrays_equal(selected_attributes, e)) {
                            is_variant_available = true
                            prices.push(variant_prices[i])
                            selected_variant_id = variant_ids[i]
                            selected_image_index = image_indexes[i]
                        }
                    })
                    if (is_variant_available) {
                        quickViewgalleryTop.slideTo(selected_image_index, 500, false)
                        mobile_image_swiper.slideTo(selected_image_index, 500, false)

                        var selected_variant_values = $('.modal-product-variants[data-id="' + selected_variant_id + '"]').attr('data-variant-values') || '';

                        if (
                            prices[0].special_price < prices[0].price &&
                            prices[0].special_price != 0
                        ) {
                            price = prices[0].special_price
                            $('#modal-product-price').text(currency + ' ' + price)

                            $('#modal-product-special-price').text(
                                currency + ' ' + prices[0].price
                            )

                            $('#modal-add-to-cart-button').attr(
                                'data-product-variant-id',
                                selected_variant_id
                            )
                            $('#modal-add-to-cart-button').attr(
                                'data-variant-values',
                                selected_variant_values
                            )
                            $('#modal-product-special-price-div').show()
                        } else {
                            price = prices[0].price
                            $('#modal-product-price').html(currency + ' ' + price)
                            $('#modal-product-special-price-div').hide()
                            $('#modal-add-to-cart-button').attr(
                                'data-product-variant-id',
                                selected_variant_id
                            )
                            $('#modal-add-to-cart-button').attr(
                                'data-variant-values',
                                selected_variant_values
                            )
                        }
                    } else {
                        $('#modal-product-special-price-div').hide()
                    }
                }
            }
        })
    })

    $('#modal-add-to-cart-button').on('click', function (e) {
        e.preventDefault()
        var qty = $('#modal-product-quantity').val()

        var title = $('#modal-product-title').text()
        var description = $('#modal-product-short-description').text()
        var image = $('.product-view-image-container img').attr('src')
        var price = $('#modal-product-price').text()

        $('#quick-view').data('data-product-id', $(this).data('productId'))
        var product_variant_id = $(this).attr('data-product-variant-id')

        var min = $(this).attr('data-min')
        var max = $(this).attr('data-max')
        var step = $(this).attr('data-step')
        var btn = $(this)
        var btn_html = $(this).html()

        if (!product_variant_id) {
            Toast.fire({
                icon: 'error',
                title: 'Please select variant'
            })
            return
        }
        $.ajax({
            type: 'POST',
            url: base_url + 'cart/manage',
            data: {
                product_variant_id: product_variant_id,
                qty: $('#modal-product-quantity').val(),
                is_saved_for_later: false,
                [csrfName]: csrfHash
            },
            dataType: 'json',
            beforeSend: function () {
                btn.html('Please Wait').text('Please Wait').attr('disabled', true)
            },
            success: function (result) {
                if (typeof result.csrfHash !== 'undefined') {
                    csrfHash = result.csrfHash;
                }
                btn.html(btn_html).attr('disabled', false)
                if (result.error == false) {
                    Toast.fire({
                        icon: 'success',
                        title: result.message
                    })
                    $('#cart-count').text(result.data.cart_count)
                    var html = ''
                    display_cart(result.data.items);
                } else {
                    if (is_loggedin == 0) {

                        Toast.fire({
                            icon: 'success',
                            title: 'Item added to cart'

                        })
                        var variant_values = $('#modal-add-to-cart-button').attr('data-variant-values') || '';
                        var cart_item = {
                            product_variant_id: product_variant_id.trim(),
                            name: title,
                            short_description: text_description,
                            qty: parseInt(qty),
                            image: image,
                            price: price.trim(),
                            variant_values: variant_values,
                            min: parseInt(min) || 1,
                            max: parseInt(max) || 100,
                            step: parseInt(step) || 1
                        }
                        var cart = localStorage.getItem('cart')
                        cart =
                            localStorage.getItem('cart') !== null ? JSON.parse(cart) : null

                        var itemExists = false;
                        if (cart !== null && cart !== undefined) {
                            for (var i = 0; i < cart.length; i++) {
                                if (cart[i].product_variant_id == product_variant_id.trim()) {
                                    cart[i].qty = parseInt(cart[i].qty) + parseInt(qty);
                                    itemExists = true;
                                    break;
                                }
                            }
                            if (!itemExists) {
                                cart.push(cart_item);
                            }
                        } else {
                            cart = [cart_item]
                        }
                        localStorage.setItem('cart', JSON.stringify(cart))
                        display_cart(cart)
                        return
                    }
                    Toast.fire({
                        icon: 'error',
                        title: result.message
                    })
                }
            }
        })
    })

    /* JS inside the modal */
    $('.auth-modal').on('click', 'header a', function (event) {
        event.preventDefault()
        window.signingIn = true
        var index = $(this).index()
        $(this).addClass('active').siblings('a').removeClass('active')
        $(this)
            .parents('div')
            .find('section')
            .eq(index)
            .removeClass('hide')
            .siblings('section')
            .addClass('hide')

        if ($(this).index() === 0) {
            $('.auth-modal .iziModal-content .icon-close').css('background', '#ddd')
        } else {
            $('.auth-modal .iziModal-content .icon-close').attr('style', '')
        }
    })

    $(document).on('opening', '.auth-modal', function (e) {
        $(this).removeClass('d-none')
        e.preventDefault()
        $('.send-otp-form')[0].reset()
        $('.send-otp-form').show()
        $('#verify-otp-form').addClass('d-none');
        $('.sign-up-form')[0].reset()
        $('.sign-up-form').hide()
        $('#is-user-exist-error').html('')
        $('#sign-up-error').html('')

        if (auth_settings == "firebase") {
            $('#recaptcha-container').html('')
            window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
                'recaptcha-container'
            )
            window.recaptchaVerifier.render().then(function (widgetId) {
                grecaptcha.reset(widgetId)
            })
        }
        var telInput = $('#phone-number'),
            errorMsg = $('#error-msg'),
            validMsg = $('#valid-msg')

        // initialise plugin
        telInput.intlTelInput({
            allowExtensions: true,
            formatOnDisplay: true,
            autoFormat: true,
            autoHideDialCode: true,
            autoPlaceholder: true,
            defaultCountry: 'in',
            ipinfoToken: 'yolo',

            nationalMode: false,
            numberType: 'MOBILE',
            preferredCountries: ['in', 'ae', 'qa', 'om', 'bh', 'kw', 'ma'],
            preventInvalidNumbers: true,
            separateDialCode: true,
            initialCountry: 'auto',
            geoIpLookup: function (callback) {
                $.get('https://ipinfo.io', function () { }, 'jsonp').always(function (
                    resp
                ) {
                    var countryCode = resp && resp.country ? resp.country : ''
                    callback(countryCode)
                })
            },
            utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/utils.js'
        })

        var reset = function () {
            telInput.removeClass('error')
            errorMsg.addClass('hide')
            validMsg.addClass('hide')
        }

        // on blur: validate
        telInput.blur(function () {
            reset()
            if ($.trim(telInput.val())) {
                if (telInput.intlTelInput('isValidNumber')) {
                    validMsg.removeClass('hide')
                } else {
                    telInput.addClass('error')
                    errorMsg.removeClass('hide')
                }
            }
        })
        // on keyup / change flag: reset
        telInput.on('keyup change', reset)
    })

    $('#quick-view').on('click', '.submit', function (event) {
        event.preventDefault()

        var fx = 'wobble', //wobble shake
            $modal = $(this).closest('.iziModal')

        if (!$modal.hasClass(fx)) {
            $modal.addClass(fx)
            setTimeout(function () {
                $modal.removeClass(fx)
            }, 1500)
        }
    })
    $('#quick-view').on('click', 'header a', function (event) {
        event.preventDefault()
        var index = $(this).index()
        $(this).addClass('active').siblings('a').removeClass('active')
        $(this)
            .parents('div')
            .find('section')
            .eq(index)
            .removeClass('hide')
            .siblings('section')
            .addClass('hide')

        if ($(this).index() === 0) {
            $('#quick-view .iziModal-content .icon-close').css('background', '#ddd')
        } else {
            $('#quick-view .iziModal-content .icon-close').attr('style', '')
        }
    })

    $('#quick-view').on('click', '.submit', function (event) {
        event.preventDefault()

        var fx = 'wobble', //wobble shake
            $modal = $(this).closest('.iziModal')

        if (!$modal.hasClass(fx)) {
            $modal.addClass(fx)
            setTimeout(function () {
                $modal.removeClass(fx)
            }, 1500)
        }
    })
    $('#quick-view').on('click', 'header a', function (event) {
        event.preventDefault()
        var index = $(this).index()
        $(this).addClass('active').siblings('a').removeClass('active')
        $(this)
            .parents('div')
            .find('section')
            .eq(index)
            .removeClass('hide')
            .siblings('section')
            .addClass('hide')

        if ($(this).index() === 0) {
            $('#quick-view .iziModal-content .icon-close').css('background', '#ddd')
        } else {
            $('#quick-view .iziModal-content .icon-close').attr('style', '')
        }
    })
});
(function () {
    function logElementEvent(eventName, element) { }

    var callback_enter = function (element) { }
    var callback_exit = function (element) { }
    var callback_loading = function (element) { }
    var callback_loaded = function (element) { }
    var callback_error = function (element) {
        'https://via.placeholder.com/440x560/?text=Error+Placeholder'
    }
    var callback_finish = function () { }
    var callback_cancel = function (element) { }

    var ll = new LazyLoad({
        threshold: 0,
        // Assign the callbacks defined above
        callback_enter: callback_enter,
        callback_exit: callback_exit,
        callback_cancel: callback_cancel,
        callback_loading: callback_loading,
        callback_loaded: callback_loaded,
        callback_error: callback_error,
        callback_finish: callback_finish
    })
})();
(function () {
    var parent = document.querySelector('.range-slider')
    if (!parent) return

    var rangeS = parent.querySelectorAll('input[type=range]'),
        numberS = parent.querySelectorAll('input[type=number]')

    rangeS.forEach(function (el) {
        el.oninput = function () {
            var slide1 = parseFloat(rangeS[0].value),
                slide2 = parseFloat(rangeS[1].value)

            if (slide1 > slide2) {
                ;
                [slide1, slide2] = [slide2, slide1]
            }

            numberS[0].value = slide1
            numberS[1].value = slide2

            custom_url = setUrlParameter(location.href, 'min-price', slide1)
            custom_url = setUrlParameter(custom_url, 'max-price', slide2)
        }
    })

    numberS.forEach(function (el) {
        el.oninput = function () {
            var number1 = parseFloat(numberS[0].value),
                number2 = parseFloat(numberS[1].value)

            if (number1 > number2) {
                var tmp = number1
                numberS[0].value = number2
                numberS[1].value = tmp
            }

            rangeS[0].value = number1
            rangeS[1].value = number2
        }
    })
})()

//Qty Counter
$(document).on('change', 'input.in-num', function (e) {
    e.preventDefault()
    var $input = $(this)
    if ($input.val() == null || typeof $input.val() == 'string') {
        if (!$.isNumeric($input.val())) {
            $input.val(1)
        } else {
            if ($input.val() == '0') {
                $input.val(1)
            }
        }
    }
})
$(document).on('focusout', '.in-num', function (e) {
    e.preventDefault()
    var value = $(this).val()
    var min = $(this).data('min')
    var step = $(this).data('step')
    var max = $(this).data('max')
    if (value < min) {
        $(this).val(min)
        Toast.fire({
            icon: 'error',
            title: 'Minimum allowed quantity is ' + min
        })
    } else if (value > max) {
        $(this).val(max)
        Toast.fire({
            icon: 'error',
            title: 'Maximum allowed quantity is ' + max
        })
    }
})
$(document).on('click', '.num-block .num-in span', function (e) {
    e.preventDefault()
    var $input = $(this).parents('.num-block').find('input.in-num')
    if ($input.val() == null) {
        $input.val(1)
    }
    if ($(this).hasClass('minus')) {
        var step = $(this).data('step')
        var count = parseFloat($input.val()) - step
        var min = $(this).data('min')
        if (count >= min) {
            $input.val(count)
        } else {
            $input.val(min)
            Toast.fire({
                icon: 'error',
                title: 'Minimum allowed quantity is ' + min
            })
        }
    } else {
        var step = $(this).data('step')
        var max = $(this).data('max')
        var count = parseFloat($input.val()) + step
        if (max != 0) {
            if (count <= max) {
                $input.val(count)
                if (count > 1) {
                    $(this).parents('.num-block').find('.minus').removeClass('dis')
                }
            } else {
                $input.val(max)
                Toast.fire({
                    icon: 'error',
                    title: 'Maximum allowed quantity is ' + max
                })
            }
        } else {
            $input.val(count)
        }
    }
    $input.change()
    return false
})

// Initialize form validation for classic theme
$(document).ready(function () {
    // Set up initial validation for login form (mobile number by default)
    $("#login_form").validate({
        ignore: ":hidden", // Ignore hidden form elements
        rules: {
            identity: {
                required: true,
                number: true,
                maxlength: 16,
            }
        }
    });
});

$(document).ready(function () {
    $('.kv-fa').rating({
        theme: 'krajee-fa',
        filledStar: '<i class="fas fa-star"></i>',
        emptyStar: '<i class="far fa-star"></i>',
        showClear: false,
        showCaption: false,
        size: 'md'
    })

    /* Set rates + misc */
    var taxRate = 0.05
    var shippingRate = 15.0
    var fadeTime = 300

    /* Assign actions */
    $(document).on(
        'change',
        '.product-quantity input,.product-sm-quantity input,.itemQty',
        function (e) {

            e.preventDefault()
            var id = $(this).data('id')
            var price = $(this).data('price')
            var qty = $(this).val()
            var temp = $(this)
            let step
            if ($(this).attr('step')) {
                step = $(this).attr('step')
            } else {
                step = $(this).data('step')
            }
            var min = parseInt($(this).attr('min'))
            var max = parseInt($(this).attr('max'))
            qty = parseInt(qty)

            if (qty <= 0 || isNaN(qty)) {
                Toast.fire({
                    icon: 'error',
                    title: `Oops! Please set minimum ${min} quantity for product`
                })
                return
            }

            if (max && !isNaN(max) && qty > max) {
                Toast.fire({
                    icon: 'error',
                    title: `Oops! Maximum allowed quantity is ${max}`
                })
                $(this).val(max)
                return
            }

            if (qty % step == 0) {
                if (is_loggedin == 1) {
                    var formData = {};
                    formData['product_variant_id'] = id;
                    formData['qty'] = qty;
                    formData[csrfName] = csrfHash;

                    $.ajax({
                        url: base_url + 'cart/manage',
                        type: 'POST',
                        data: formData,
                        dataType: 'json',
                        success: function (result) {
                            // Update CSRF token with new value from server
                            if (typeof result.csrfHash !== 'undefined') {
                                csrfHash = result.csrfHash;
                            }
                            if (result.error == false) {
                                updateQuantity(temp, price)
                            } else {
                                Toast.fire({
                                    icon: 'error',
                                    title: result.message
                                })
                            }
                        },
                        // error: function (xhr, status, error) {
                        //     Toast.fire({
                        //         icon: 'error',
                        //         title: 'Error updating cart: ' + error
                        //     })
                        //     console.error('AJAX Error:', xhr.responseText);
                        // }
                    })
                } else {
                    var cart = localStorage.getItem('cart')
                    cart = localStorage.getItem('cart') !== null ? JSON.parse(cart) : null
                    if (cart) {
                        cart.forEach(function (item) {
                            if (item.product_variant_id == id) {
                                item.qty = qty
                            }
                        })
                        localStorage.setItem('cart', JSON.stringify(cart))
                    }
                    updateQuantity(temp, price)
                }
            } else {
                Toast.fire({
                    icon: 'error',
                    title: `Oops! you can only set quantity in step size of ${step}`
                })
            }
        }
    )

    //Remove from Cart.
    $(document).on(
        'click',
        '.product-removal button,.product-removal i,.product-sm-removal button',
        function (e) {
            e.preventDefault()
            var id = $(this).data('id')
            var is_save_for_later =
                typeof $(this).data('is-save-for-later') != 'undefined' &&
                    $(this).data('is-save-for-later') == 1 ?
                    '1' :
                    '0'
            var product = $(this).parent().parent().parent()
            if (confirm('Are you sure want to remove this?')) {
                if (is_loggedin == 1) {
                    // remove from server
                    $.ajax({
                        url: base_url + 'cart/remove',
                        type: 'POST',
                        data: {
                            product_variant_id: id,
                            is_save_for_later: is_save_for_later,
                            [csrfName]: csrfHash
                        },
                        dataType: 'json',
                        success: function (result) {
                            if (typeof result.csrfHash !== 'undefined') {
                                csrfHash = result.csrfHash;
                            }
                            if (typeof result.csrfName !== 'undefined') {
                                csrfName = result.csrfName;
                            }

                            if (result.error == false) {
                                var cart_count = $('#cart-count').text()
                                cart_count--
                                $('#cart-count').text(cart_count > 0 ? cart_count : '')
                                removeItem(product)
                                if (cart_count <= 0) {
                                    $('#cart-item-sidebar').html('<h1 class="h4 text-center">Your Cart Is Empty</h1>')
                                }

                                Toast.fire({
                                    icon: 'success',
                                    title: 'Item removed successfully'
                                })

                                setTimeout(function () {
                                    location.reload();
                                }, 400);
                            } else {
                                Toast.fire({
                                    icon: 'error',
                                    title: result.message
                                })
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('Remove cart item error:', error);
                            console.error('Response:', xhr.responseText);
                            Toast.fire({
                                icon: 'error',
                                title: 'Failed to remove item. Please try again.'
                            })
                        }
                    })
                } else {
                    // remove from local storage
                    removeItem(product)
                    var cart = localStorage.getItem('cart')
                    cart = localStorage.getItem('cart') !== null ? JSON.parse(cart) : null
                    if (cart) {
                        var new_cart = cart.filter(function (item) {
                            return item.product_variant_id != id
                        })
                        localStorage.setItem('cart', JSON.stringify(new_cart))
                        var cart_count = new_cart.length
                        $('#cart-count').text(cart_count > 0 ? cart_count : '')
                        if (new_cart.length > 0) {
                            display_cart(new_cart)
                        } else {
                            $('#cart-item-sidebar').html('<h1 class="h4 text-center">Your Cart Is Empty</h1>')
                        }
                    }
                }
            }
        }
    )

    /* Recalculate cart */
    function recalculateCart() {
        var subtotal = 0

        /* Sum up row totals */
        $('.product').each(function () {
            subtotal += parseFloat($(this).children('.product-line-price').text())
        })

        /* Calculate totals */
        var tax = subtotal * taxRate
        var shipping = subtotal > 0 ? shippingRate : 0
        var total = subtotal + tax + shipping

        /* Update totals display */
        $('.totals-value').fadeOut(fadeTime, function () {
            $('#cart-subtotal').html(subtotal.toFixed(2))
            $('#cart-tax').html(tax.toFixed(2))
            $('#cart-shipping').html(shipping.toFixed(2))
            $('#cart-total').html(total.toFixed(2))
            if (total == 0) {
                $('.checkout').fadeOut(fadeTime)
            } else {
                $('.checkout').fadeIn(fadeTime)
            }
            $('.totals-value').fadeIn(fadeTime)
        })
    }

    /* Update quantity */
    function updateQuantity(quantityInput, price) {
        /* Calculate line price */
        if (quantityInput.data('page') == 'cart') {
            var productRow = $(quantityInput)
                .parent()
                .parent()
                .parent()
                .siblings('.total-price')
        } else {
            var productRow = $(quantityInput).parent().parent()
        }
        var quantity = parseFloat($(quantityInput).val())
        var itemPrice = parseFloat(price)
        var linePrice = itemPrice * quantity
        /* Update line price display and recalc cart totals */
        productRow.children('.product-line-price').each(function () {
            $(this).fadeOut(fadeTime, function () {
                $(this).text(currency + ' ' + linePrice.toFixed(2))
                recalculateCart()
                mycartTotal()
                $(this).fadeIn(fadeTime)
            })
        })
    }

    /* Remove item from cart */
    function removeItem(removeProduct) {
        /* Remove row from DOM and recalc cart total */
        var productRow = $(removeProduct)
        productRow.slideUp(fadeTime, function () {
            productRow.remove()
            recalculateCart()
            mycartTotal()
        })
    }

    window.editAddress = {
        'click .edit-address': function (e, value, row, index) {
            $("#address_id").val(row.id);
            $("#edit_name").val(row.name);
            $("#edit_area").val(row.area);
            $("#edit_mobile").val(row.mobile);
            $("#edit_address").val(row.address);
            $("#edit_state").val(row.state);
            $("#edit_country").val(row.country);
            $("#edit_pincode").val(row.pincode);
            if (row.city_id == 0 || row.city_id == "") {
                $('.edit_area').addClass('d-none');
                $('.edit_pincode').addClass('d-none');
                $('.other_areas').removeClass('d-none');
                $("#other_areas_value").val(row.area);
                $('.other_city').removeClass('d-none');
                $("#other_city_value").val(row.area);
                $('.other_pincode').removeClass('d-none');
                $("#other_pincode_value").val(row.pincode);
                $("#edit_city").val(row.city_id);
            } else if (row.system_pincode == 0) {
                $("#edit_city").val(row.city_id).trigger('change', [row.pincode]);
                $('.other_pincode').removeClass('d-none');
                $("#other_pincode_value").val(row.pincode);
            } else {
                $("#edit_city").val(row.city_id).trigger('change', [row.pincode]);
            }

            $('input[type=radio][value=' + row.type.toLowerCase() + ']').attr('checked', true);
        }
    };
})

$('.js-menu').on('click', () => {
    $('.js-menu').toggleClass('active')
    $('.js-filter-nav').toggleClass('open')
    $('.js-filter-nav__list').toggleClass('show')
    if ($('body').css('overflow').toLowerCase() == 'hidden') {
        $('body').css('overflow', 'scroll')
    } else {
        $('body').css('overflow', 'hidden')
    }
})

jQuery(document).ready(function ($) {
    function morphDropdown(element) {
        this.element = element
        this.mainNavigation = this.element.find('.main-nav')
        this.mainNavigationItems = this.mainNavigation.find('.has-dropdown')
        this.dropdownList = this.element.find('.dropdown-list')
        this.dropdownWrappers = this.dropdownList.find('.dropdown')
        this.dropdownItems = this.dropdownList.find('.content')
        this.dropdownBg = this.dropdownList.find('.bg-layer')
        this.mq = this.checkMq()
        this.bindEvents()
    }

    morphDropdown.prototype.checkMq = function () {
        //check screen size
        var self = this
        return window
            .getComputedStyle(self.element.get(0), '::before')
            .getPropertyValue('content')
            .replace(/'/g, '')
            .replace(/"/g, '')
            .split(', ')
    }

    morphDropdown.prototype.bindEvents = function () {
        var self = this
        //hover over an item in the main navigation
        this.mainNavigationItems
            .mouseenter(function (event) {
                //hover over one of the nav items -> show dropdown
                self.showDropdown($(this))
            })
            .mouseleave(function () {
                setTimeout(function () {
                    //if not hovering over a nav item or a dropdown -> hide dropdown
                    if (
                        self.mainNavigation.find('.has-dropdown:hover').length == 0 &&
                        self.element.find('.dropdown-list:hover').length == 0
                    )
                        self.hideDropdown()
                }, 50)
            })

        //hover over the dropdown
        this.dropdownList.mouseleave(function () {
            setTimeout(function () {
                //if not hovering over a dropdown or a nav item -> hide dropdown
                self.mainNavigation.find('.has-dropdown:hover').length == 0 &&
                    self.element.find('.dropdown-list:hover').length == 0 &&
                    self.hideDropdown()
            }, 50)
        })

        //click on an item in the main navigation -> open a dropdown on a touch device
        this.mainNavigationItems.on('touchstart', function (event) {
            var selectedDropdown = self.dropdownList.find(
                '#' + $(this).data('content')
            )
            if (
                !self.element.hasClass('is-dropdown-visible') ||
                !selectedDropdown.hasClass('active')
            ) {
                event.preventDefault()
                self.showDropdown($(this))
            }
        })
    }

    morphDropdown.prototype.showDropdown = function (item) {
        this.mq = this.checkMq()
        if (this.mq == 'desktop') {
            var self = this
            var selectedDropdown = this.dropdownList.find('#' + item.data('content'))
            var selectedDropdownHeight = selectedDropdown.innerHeight() + 18
            var width =
                selectedDropdown.children('.content').children('ul').children('li')
                    .length * 180
            if (width > 540) {
                width = 540
            }
            var selectedDropdownWidth = parseInt(width),
                selectedDropdownLeft =
                    item.offset().left + item.innerWidth() / 2 - selectedDropdownWidth / 2
            var dropdownWrapperLeft = item[0].offsetParent.offsetLeft
            //update dropdown position and size
            this.updateDropdown(
                selectedDropdown,
                parseInt(selectedDropdownHeight),
                selectedDropdownWidth,
                parseInt(selectedDropdownLeft)
            )
            //add active class to the proper dropdown item
            this.element.find('.active').removeClass('active')
            this.element.find('.morph-dropdown-wrapper').css({
                '-moz-transform': 'translateX(-' + dropdownWrapperLeft + 'px)',
                '-webkit-transform': 'translateX(-' + dropdownWrapperLeft + 'px)',
                '-ms-transform': 'translateX(-' + dropdownWrapperLeft + 'px)',
                '-o-transform': 'translateX(-' + dropdownWrapperLeft + 'px)',
                transform: 'translateX(-' + dropdownWrapperLeft + 'px)'
            })

            selectedDropdown
                .addClass('active')
                .removeClass('move-left move-right')
                .prevAll()
                .addClass('move-left')
                .end()
                .nextAll()
                .addClass('move-right')
            item.addClass('active')
            //show the dropdown wrapper if not visible yet
            if (!this.element.hasClass('is-dropdown-visible')) {
                setTimeout(function () {
                    self.element.addClass('is-dropdown-visible')
                }, 10)
            }
        }
    }

    morphDropdown.prototype.updateDropdown = function (
        dropdownItem,
        height,
        width,
        left
    ) {
        this.dropdownList.css({
            '-moz-transform': 'translateX(' + left + 'px)',
            '-webkit-transform': 'translateX(' + left + 'px)',
            '-ms-transform': 'translateX(' + left + 'px)',
            '-o-transform': 'translateX(' + left + 'px)',
            transform: 'translateX(' + left + 'px)',
            width: width + 'px',
            height: height + 'px'
        })

        this.dropdownBg.css({
            '-moz-transform': 'scaleX(' + width + ') scaleY(' + height + ')',
            '-webkit-transform': 'scaleX(' + width + ') scaleY(' + height + ')',
            '-ms-transform': 'scaleX(' + width + ') scaleY(' + height + ')',
            '-o-transform': 'scaleX(' + width + ') scaleY(' + height + ')',
            transform: 'scaleX(' + width + ') scaleY(' + height + ')'
        })
    }

    morphDropdown.prototype.hideDropdown = function () {
        this.mq = this.checkMq()
        if (this.mq == 'desktop') {
            this.element
                .removeClass('is-dropdown-visible')
                .find('.active')
                .removeClass('active')
                .end()
                .find('.move-left')
                .removeClass('move-left')
                .end()
                .find('.move-right')
                .removeClass('move-right')
        }
    }

    morphDropdown.prototype.resetDropdown = function () {
        this.mq = this.checkMq()
        if (this.mq == 'mobile') {
            this.dropdownList.removeAttr('style')
        }
    }

    var morphDropdowns = []
    if ($('.cd-morph-dropdown').length > 0) {
        $('.cd-morph-dropdown').each(function () {
            //create a morphDropdown object for each .cd-morph-dropdown
            morphDropdowns.push(new morphDropdown($(this)))
        })

        var resizing = false

        //on resize, reset dropdown style property
        updateDropdownPosition()
        $(window).on('resize', function () {
            if (!resizing) {
                resizing = true
                !window.requestAnimationFrame ?
                    setTimeout(updateDropdownPosition, 300) :
                    window.requestAnimationFrame(updateDropdownPosition)
            }
        })

        function updateDropdownPosition() {
            morphDropdowns.forEach(function (element) {
                element.resetDropdown()
            })

            resizing = false
        }
    }
})

$('.navbar-top-search-box input').on('focus', function () {
    $('.navbar-top-search-box .input-group-text').css('border-color', '#0e7dd1')
})
$('.navbar-top-search-box input').on('blur', function () {
    $('.navbar-top-search-box .input-group-text').css(
        'border',
        '1px solid #ced4da'
    )
})

// Initialize Swiper
//Swiper1 For Home Page Slider
var swiper = new Swiper('.swiper1', {
    loop: true,
    preloadImages: false,
    lazy: true,
    autoplay: {
        delay: 6000,
        disableOnInteraction: false
    },
    pagination: {
        el: '.swiper1-pagination',
        clickable: true
    },
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev'
    }
})

var swiperheader = new Swiper('.imageSliderHeader', {
    autoplay: {
        delay: 6000
    },
    autoplay: {
        delay: 6000,
        disableOnInteraction: false
    },
    pagination: {
        el: '.imageSliderHeader-pagination',
        clickable: true
    },
    loop: true,
    grabCursor: true
})

//preview-image-swiper
var swiperF = new Swiper('.preview-image-swiper', {
    pagination: {
        el: '.preview-image-swiper-pagination'
    }
})

//banner-swiper
var swiperV = new Swiper('.banner-swiper', {
    preloadImages: false,
    lazy: true,
    autoplay: true,
    pagination: {
        el: '.banner-swiper-pagination'
    },
    loop: true,
    // Navigation arrows
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev'
    }
})

//category-swiper
var swiperS = new Swiper('.category-swiper', {
    slidesPerView: 5,
    preloadImages: false,
    lazyLoading: true,
    updateOnImagesReady: false,
    lazyLoadingInPrevNextAmount: 0,
    pagination: {
        el: '.category-swiper-pagination',
        clickable: true
    },
    breakpoints: {
        350: {
            slidesPerView: 4,
            spaceBetweenSlides: 10
        },
        400: {
            slidesPerView: 4,
            spaceBetweenSlides: 10
        },
        499: {
            slidesPerView: 4,
            spaceBetweenSlides: 10
        },
        550: {
            slidesPerView: 1,
            spaceBetweenSlides: 10
        },
        600: {
            slidesPerView: 2,
            spaceBetweenSlides: 10
        },
        700: {
            slidesPerView: 3,
            spaceBetweenSlides: 10
        },
        800: {
            slidesPerView: 4,
            spaceBetweenSlides: 10
        },
        999: {
            slidesPerView: 5,
            spaceBetweenSlides: 10
        },
        1900: {
            slidesPerView: 6,
            spaceBetweenSlides: 10
        },
        1900: {
            slidesPerView: 6,
            spaceBetweenSlides: 10
        }
    }
})

document.querySelectorAll('.product-image-swiper').forEach(function (elem) {
    new Swiper(elem, {
        grabCursor: true,
        preloadImages: false,
        lazyLoading: true,
        updateOnImagesReady: false,
        lazyLoadingInPrevNextAmount: 1,
        navigation: {
            nextEl: elem.nextElementSibling,
            prevEl: elem.nextElementSibling.nextElementSibling
        },
        breakpoints: {
            350: {
                slidesPerView: 1,
                spaceBetweenSlides: 10
            },
            400: {
                slidesPerView: 1,
                spaceBetweenSlides: 10
            },
            499: {
                slidesPerView: 1,
                spaceBetweenSlides: 10
            },
            550: {
                slidesPerView: 1,
                spaceBetweenSlides: 10
            },
            600: {
                slidesPerView: 2,
                spaceBetweenSlides: 10
            },
            700: {
                slidesPerView: 3,
                spaceBetweenSlides: 10
            },
            800: {
                slidesPerView: 4,
                spaceBetweenSlides: 10
            },
            999: {
                slidesPerView: 5,
                spaceBetweenSlides: 10
            },
            1900: {
                slidesPerView: 6,
                spaceBetweenSlides: 10
            },
            1900: {
                slidesPerView: 6,
                spaceBetweenSlides: 10
            }
        }
    })
})

var swiperH = new Swiper('.swiper2', {
    slidesPerView: 'auto',
    grabCursor: true,
    spaceBetween: 20,
    pagination: {
        el: '.swiper2-pagination',
        clickable: true
    }
})

//Gallery Swiper
var galleryThumbs = new Swiper('.gallery-thumbs-1', {
    spaceBetween: 10,
    slidesPerView: 4,
    freeMode: true,
    watchSlidesVisibility: true,
    watchSlidesProgress: true
})
var galleryTop = new Swiper('.gallery-top-1', {
    spaceBetween: 10,
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev'
    },
    thumbs: {
        swiper: galleryThumbs
    }
})

$(document).ready(function () {
    // Using custom configuration
    var zoomConfig = {
        zoomWindowFadeIn: 500,
        zoomLensFadeIn: 500,
        gallery: 'gal1',
        imageCrossfade: true,
        zoomWindowWidth: 411,
        zoomWindowHeight: 274,
        zoomWindowOffsetX: 10,
        scrollZoom: true,
        cursor: 'pointer',
        tint: true,
        tintColour: '#0E7DD1',
        tintOpacity: 0.5
    }
    var zoomImage = $('img#img_01')
    zoomImage.ezPlus()

    zoomImage.bind('click', function (e) {
        var ez = $('#img_01').data('ezPlus')
        return false
    })
})


$(document).ready(function () {
    $('.open-navbar-mobile').on('click', function (event) {
        event.preventDefault();
        $('.block-div').css('width', '100%')
        $('body').css('overflow', 'hidden')
        $('#mySidenav').removeClass('is-closed-left')
    });
});

$(document).ready(function () {
    $('.shopping-cart-sidebar-btn').on('click', function (event) {
        event.preventDefault();
        $('.block-div').css('width', '100%');
        $('body').css('overflow', 'hidden');
        $('.shopping-cart-sidebar').removeClass('is-closed-right');
    });
});

$(document).ready(function () {
    $('.cart-sidebar-div').on('click', function () {
        $('.block-div').css('width', '0%');
        $('body').css('overflow', 'unset');
        $('.shopping-cart-sidebar').addClass('is-closed-right');
        $('#mySidenav').addClass('is-closed-left');
    });
});


$(document).ready(function () {
    jQuery(document).ready(function () {
        jQuery('#jquery-accordion-menu').jqueryAccordionMenu()
        jQuery('.colors a').click(function () {
            if ($(this).attr('class') != 'default') {
                $('#jquery-accordion-menu').removeClass()
                $('#jquery-accordion-menu')
                    .addClass('jquery-accordion-menu')
                    .addClass($(this).attr('class'))
            } else {
                $('#jquery-accordion-menu').removeClass()
                $('#jquery-accordion-menu').addClass('jquery-accordion-menu')
            }
        })
    })
});
(function ($, window, document, undefined) {
    var pluginName = 'jqueryAccordionMenu'
    var defaults = {
        speed: 300,
        showDelay: 0,
        hideDelay: 0,
        singleOpen: true,
        clickEffect: true
    }

    function Plugin(element, options) {
        this.element = element
        this.settings = $.extend({}, defaults, options)
        this._defaults = defaults
        this._name = pluginName
        this.init()
    }
    $.extend(Plugin.prototype, {
        init: function () {
            this.openSubmenu()
            this.submenuIndicators()
            if (defaults.clickEffect) {
                this.addClickEffect()
            }
        },
        openSubmenu: function () {
            $(this.element)
                .children('ul')
                .find('li')
                .bind('click touchstart', function (e) {
                    e.stopPropagation()
                    e.preventDefault()
                    if ($(this).children('.submenu').length > 0) {
                        if ($(this).children('.submenu').css('display') == 'none') {
                            $(this).children('.submenu').show(defaults.speed)
                            $(this)
                                .children('.submenu')
                                .siblings('a')
                                .addClass('submenu-indicator-minus')
                            if (defaults.singleOpen) {
                                $(this).siblings().children('.submenu').hide(defaults.speed)
                                $(this)
                                    .siblings()
                                    .children('.submenu')
                                    .siblings('a')
                                    .removeClass('submenu-indicator-minus')
                            }
                            return false
                        } else {
                            $(this)
                                .children('.submenu')
                                .delay(defaults.hideDelay)
                                .hide(defaults.speed)
                        }
                        if (
                            $(this)
                                .children('.submenu')
                                .siblings('a')
                                .hasClass('submenu-indicator-minus')
                        ) {
                            $(this)
                                .children('.submenu')
                                .siblings('a')
                                .removeClass('submenu-indicator-minus')
                        }
                    }
                    window.location.href = $(this).children('a').attr('href')
                })
        },
        submenuIndicators: function () {
            if ($(this.element).find('.submenu').length > 0) {
                $(this.element)
                    .find('.submenu')
                    .siblings('a')
                    .append("<span class='submenu-indicator'>+</span>")
            }
        },
        addClickEffect: function () {
            var ink, d, x, y

            $(this.element)
                .find('a > .submenu-indicator')
                .on('click touchstart', function (e) {
                    $('.ink').remove()
                    if ($(this).children('.ink').length === 0) {
                        $(this).prepend("<span class='ink'></span>")
                    }
                    ink = $(this).find('.ink')
                    ink.removeClass('animate-ink')
                    if (!ink.height() && !ink.width()) {
                        d = Math.max($(this).outerWidth(), $(this).outerHeight())
                        ink.css({
                            height: d,
                            width: d
                        })
                    }
                    x = e.pageX - $(this).offset().left - ink.width() / 2
                    y = e.pageY - $(this).offset().top - ink.height() / 2
                    ink
                        .css({
                            top: y + 'px',
                            left: x + 'px'
                        })
                        .addClass('animate-ink')
                })
        }
    })
    $.fn[pluginName] = function (options) {
        this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options))
            }
        })
        return this
    }
})(jQuery, window, document)

document.addEventListener('DOMContentLoaded', function (event) {
    const cartButtons = document.querySelectorAll('.cart-button')

    cartButtons.forEach(button => {
        button.addEventListener('click', cartClick)
    })

    function cartClick() {
        let button = this
        button.classList.add('clicked')
    }
})

// timer
var timer

var compareDate = new Date()
compareDate.setDate(compareDate.getDate() + 7) //just for this demo today + 7 days

timer = setInterval(function () {
    timeBetweenDates(compareDate)
}, 1000)

function timeBetweenDates(toDate) {
    var dateEntered = toDate
    var now = new Date()
    var difference = dateEntered.getTime() - now.getTime()

    if (difference <= 0) {
        // Timer done
        clearInterval(timer)
    } else {
        var seconds = Math.floor(difference / 1000)
        var minutes = Math.floor(seconds / 60)
        var hours = Math.floor(minutes / 60)
        var days = Math.floor(hours / 24)

        hours %= 24
        minutes %= 60
        seconds %= 60

        $('#days').text(days)
        $('#hours').text(hours)
        $('#minutes').text(minutes)
        $('#seconds').text(seconds)
    }
}

// back-to-top

$(window).scroll(function () {
    if ($(this).scrollTop() > 50) {
        $('.back-to-top:hidden').stop(true, true).fadeIn()
    } else {
        $('.back-to-top').stop(true, true).fadeOut()
    }
})
$(function () {
    $('.scroll').click(function () {
        $('html,body').animate({
            scrollTop: $('.sidenav').offset().top
        },
            '1000'
        )
        return false
    })
})

// newsletter

$('#newsletter-modal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget) // Button that triggered the modal
    var recipient = button.data('whatever') // Extract info from data-* attributes
})

// client swipet slider

var swiper = new Swiper('.swiper-container-client', {
    loop: true,
    // Add the slides to loop
    loopedSlides: 10,
    autoheight: true,
    slidesPerView: 2,
    spaceBetween: 30,
    autoplay: {
        delay: 6000,
        disableOnInteraction: false
    },
    breakpoints: {
        600: {
            slidesPerView: 6,
            spaceBetween: 20
        }
    },
    pagination: {
        el: '.swiper-pagination',
        clickable: true
    }
})
jQuery(document).ready(function ($) {
    $('.get_e_time').each((val, element) => {
        get_flash_sale_timer(element)
    })
})

// color switcher
jQuery(document).ready(function ($) {
    $('ul.color-style .blue').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/blue.css'
        )
        return false
    })

    $('ul.color-style .cyan-dark').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/cyan-dark.css'
        )
        return false
    })

    $('ul.color-style .dark-blue').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/dark-blue.css'
        )
        return false
    })

    $('ul.color-style .dark-purple').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/dark-purple.css'
        )
        return false
    })

    $('ul.color-style .default').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/default.css'
        )
        return false
    })

    $('ul.color-style .green').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/green.css'
        )
        return false
    })

    $('ul.color-style .indigo').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/indigo.css'
        )
        return false
    })

    $('ul.color-style .orange').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/orange.css'
        )
        return false
    })

    $('ul.color-style .peach').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/peach.css'
        )
        return false
    })

    $('ul.color-style .pink').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/pink.css'
        )
        return false
    })
    $('ul.color-style .purple').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/purple.css'
        )
        return false
    })
    $('ul.color-style .red').click(function () {
        $('#color-switcher').attr(
            'href',
            base_url + 'assets/front_end/classic/css/colors/red.css'
        )
        return false
    })

    $('ul.color-style li a').click(function (e) {
        e.preventDefault()
        $(this).parent().parent().find('a').removeClass('active')
        $(this).addClass('active')
    })

    $('#colors-switcher .color-bottom a.settings').click(function (e) {
        e.preventDefault()
        var div = $('#colors-switcher')
        if (div.css(mode) === '-189px') {
            $('#colors-switcher').animate({
                [mode]: '0px'
            })
        } else {
            $('#colors-switcher').animate({
                [mode]: '-189px'
            })
        }
    })
    $('#colors-switcher').animate({
        [mode]: '-189px'
    })
})

/**
 * Product Listing Page Starts
 */
$('#back_to_top').on('click', function () {
    $('html, body').animate({
        scrollTop: 0
    }, 'slow')
})
$('#per_page_products a').on('click', function (e) {
    e.preventDefault()
    var per_page = $(this).data('value')
    $(this).parent().siblings('a.dropdown-toggle').text($(this).text())
    location.href = setUrlParameter(location.href, 'per-page', per_page)
})


$('#product_sort_by').on('change', function (e) {
    e.preventDefault()
    var sort = $(this).val()
    location.href = setUrlParameter(location.href, 'sort', sort)
})

$('.sub-category').on('click', function (e) {
    e.preventDefault()
    var category = $(this).data('value')
    custom_url = setUrlParameter(custom_url, 'category', category)
    location.href = custom_url
})

$(document).on('change', '.product_attributes', function (e) {
    e.preventDefault()
    var attribute_name = $(this).data('attribute')
    attribute_name = 'filter-' + attribute_name
    var get_param = getUrlParameter(attribute_name)
    var current_param_value = $(this).val()
    if (get_param == undefined) {
        get_param = ''
    }
    if (this.checked) {
        var param = buildUrlParameterValue(
            attribute_name,
            current_param_value,
            'add',
            custom_url
        )
    } else {
        var param = buildUrlParameterValue(
            attribute_name,
            current_param_value,
            'remove',
            custom_url
        )
    }
    custom_url = setUrlParameter(custom_url, attribute_name, param)
})
$('.product_filter_btn').on('click', function (e) {
    e.preventDefault();
    location.href = custom_url;
});

$('.product_reset_btn').on('click', function (e) {
    e.preventDefault();
    location.href = base_url + 'products'; // reset to default page
});



function buildUrlParameterValue(
    paramName,
    paramValue,
    action,
    custom_url = ''
) {
    if (custom_url != '') {
        var param = getUrlParameter(paramName, custom_url)
    } else {
        var param = getUrlParameter(paramName)
    }
    if (action == 'add') {
        if (param == undefined) {
            param = paramValue
        } else {
            param += '|' + paramValue
        }
        return param
    } else if (action == 'remove') {
        if (param != undefined) {
            param = param.split('|')
            param.splice($.inArray(paramValue, param), 1)
            return param.join('|')
        } else {
            return ''
        }
    }
}

function getUrlParameter(sParam, custom_url = '') {
    sParam = sParam.replace(/\s+/g, '-')
    if (custom_url != '') {
        if (custom_url.indexOf('?') > -1) {
            var sPageURL = custom_url.substring(custom_url.indexOf('?') + 1)
        } else {
            return undefined
        }
    } else {
        var sPageURL = window.location.search.substring(1)
    }

    var sURLVariables = sPageURL.split('&'),
        sParameterName,
        i

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=')

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ?
                true :
                decodeURIComponent(sParameterName[1])
        }
    }
}

function checkUrlHasParam(custom_url = '') {
    if (custom_url == '') {
        custom_url = window.location.href
    }

    if (custom_url.indexOf('?') > -1) {
        return true
    } else {
        return undefined
    }
}

function setUrlParameter(url, paramName, paramValue) {
    paramName = paramName.replace(/\s+/g, '-')
    if (paramValue == null || paramValue == '') {
        return url
            .replace(new RegExp('[?&]' + paramName + '=[^&#]*(#.*)?$'), '$1')
            .replace(new RegExp('([?&])' + paramName + '=[^&]*&'), '$1')
    }
    var pattern = new RegExp('\\b(' + paramName + '=).*?(&|#|$)')
    if (url.search(pattern) >= 0) {
        return url.replace(pattern, '$1' + paramValue + '$2')
    }
    url = url.replace(/[?#]$/, '')
    return url + (url.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue
}

//Set URL in Product Listing Page Style buttons
var type_url = ''
type_url = setUrlParameter(custom_url, 'type', null)
$('#product_grid_view_btn').attr('href', type_url)
type_url = setUrlParameter(custom_url, 'type', 'list')
$('#product_list_view_btn').attr('href', type_url)
if (getUrlParameter('type') == 'list') {
    $('#product_list_view_btn').addClass('active')
} else {
    $('#product_grid_view_btn').addClass('active')
}

/**
 * Product Listing Page Ends
 */
$('#category_parent').each(function () {
    $(this).select2({
        theme: 'bootstrap4',
        width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
        placeholder: $(this).data('placeholder'),
        allowClear: Boolean($(this).data('allow-clear')),
        dropdownCssClass: "test",
        templateResult: function (data) {
            // We only really care if there is an element to pull classes from
            if (!data.element) {
                return data.text;
            }

            var $element = $(data.element);

            var $wrapper = $('<span></span>');
            $wrapper.addClass($element[0].className);

            $wrapper.text(data.text);

            return $wrapper;
        }
    });
});

$('#category_parent').on('change', function (e) {
    e.preventDefault();
    var category_id = $(this).val();
    location.href = setUrlParameter(location.href, 'category_id', category_id);
});
$('#blog_search').on('change', function (e) {
    e.preventDefault();
    var blog_search = $(this).val();
    location.href = setUrlParameter(location.href, 'blog_search', blog_search);
});
/**
 * Login and Register Model
 */
$('.auth_model').on('click', function (e) {
    e.preventDefault()
    var value = $(this).data('value')
    $('#forgot_password_div').addClass('hide')
    if (value == 'login') {
        $('#login_div').removeClass('hide')
        $('#login').addClass('active')

        $('#register_div').addClass('hide')
        $('#register').removeClass('active')
    } else if (value == 'register') {
        $('#login_div').addClass('hide')
        $('#login').removeClass('active')

        $('#register_div').removeClass('hide')
        $('#register').addClass('active')
    }
    $('.block-div').css('width', '0%');
    $('body').css('overflow', 'unset');
    $('.shopping-cart-sidebar').addClass('is-closed-right');
    $('#mySidenav').addClass('is-closed-left');
})

// Product Details Page.
$('.attributes').on('change', function (e) {
    e.preventDefault()
    var selected_attributes = []
    var attributes_length = ''
    var price = ''
    var is_variant_available = false
    var variant = []
    var prices = []
    var variant_prices = []
    var variants = []
    var variant_ids = []
    var image_indexes = []
    var selected_image_index
    $('.variants').each(function () {
        prices = {
            price: $(this).data('price'),
            special_price: $(this).data('special_price')
        }
        variant_ids.push($(this).data('id'))
        variant_prices.push(prices)
        variant = $(this).val().split(',')
        variants.push(variant)
        image_indexes.push($(this).data('image-index'))
    })

    attributes_length = variant.length
    $('.attributes').each(function (i, e) {
        if ($(this).prop('checked')) {
            selected_attributes.push($(this).val())
            if (selected_attributes.length == attributes_length) {
                /* compare the arrays */
                prices = []
                var selected_variant_id = ''
                $.each(variants, function (i, e) {
                    if (arrays_equal(selected_attributes, e)) {
                        is_variant_available = true
                        prices.push(variant_prices[i])
                        selected_variant_id = variant_ids[i]
                        selected_image_index = image_indexes[i]
                    }
                })
                if (is_variant_available) {
                    $('#add_cart').attr('data-product-variant-id', selected_variant_id)
                    galleryTop.slideTo(selected_image_index, 500, false)
                    swiperF.slideTo(selected_image_index, 500, false)
                    if (
                        prices[0].special_price < prices[0].price &&
                        prices[0].special_price != 0
                    ) {
                        price = prices[0].special_price
                        $('#add_cart').attr('data-product-price', price)
                        $('#buy_it_now').attr('data-product-price', price)
                        $('#price').html(currency + ' ' + price)
                        $('#striped-price').html(currency + ' ' + prices[0].price)
                        $('#striped-price-div').show()
                        $('#add_cart').removeAttr('disabled')
                    } else {
                        price = prices[0].price
                        $('#add_cart').attr('data-product-price', price)
                        $('#buy_it_now').attr('data-product-price', price)
                        $('#price').html(currency + ' ' + price)
                        $('#striped-price-div').hide()
                        $('#add_cart').removeAttr('disabled')
                    }
                } else {
                    price = '<small class="text-danger h5">No Variant available!</small>'
                    $('#price').html(price)
                    $('#striped-price-div').hide()
                    $('#striped-price').html('')
                    $('#add_cart').attr('disabled', 'true')
                }
            }
        }
    })
    variants = ''
})

function arrays_equal(_arr1, _arr2) {
    if (
        !Array.isArray(_arr1) ||
        !Array.isArray(_arr2) ||
        _arr1.length !== _arr2.length
    ) {
        return false
    }

    const arr1 = _arr1.concat().sort()
    const arr2 = _arr2.concat().sort()

    for (let i = 0; i < arr1.length; i++) {
        if (arr1[i] !== arr2[i]) {
            return false
        }
    }

    return true
}

$(document).on('click', '.add_to_cart', function (e) {
    e.preventDefault()
    var qty = $('[name="qty"]').val()
    $('#quick-view').data('data-product-id', $(this).data('productId'))
    var product_variant_id = $(this).attr('data-product-variant-id')
    var title = $(this).attr('data-product-title')
    var image = $(this).attr('data-product-image')
    var price = $(this).attr('data-product-price')
    var description = $(this).attr('data-product-description')
    var variant_values = $(this).attr('data-variant-values') || ''
    var min = $(this).attr('data-min')
    var max = $(this).attr('data-max')
    var step = $(this).attr('data-step')
    var btn = $(this)
    var btn_html = $(this).html()
    var izi_modal = $(this).attr('data-izimodal-open')

    if (!product_variant_id) {
        Toast.fire({
            icon: 'error',
            title: 'Please select variant'
        })
        return
    }

    if (is_loggedin == 0 && (!price || price === 'undefined' || price === '')) {
        Toast.fire({
            icon: 'error',
            title: 'Price not available. Please select a variant.'
        })
        return
    }
    if (izi_modal == '' || izi_modal == undefined) {
        $.ajax({
            type: 'POST',
            url: base_url + 'cart/manage',
            data: {
                product_variant_id: product_variant_id,
                qty: qty,
                is_saved_for_later: false,
                [csrfName]: csrfHash
            },
            dataType: 'json',
            beforeSend: function () {
                btn.html('Please Wait').text('Please Wait').attr('disabled', true)
            },
            success: function (result) {
                if (typeof result.csrfHash !== 'undefined') {
                    csrfHash = result.csrfHash;
                }
                btn.html(btn_html).attr('disabled', false)
                if (result.error == false) {
                    Toast.fire({
                        icon: 'success',
                        title: result.message
                    })
                    $('#cart-count').text(result.data.cart_count)
                    var html = ''

                    if (is_loggedin == 0) {
                        display_cart(result.data.items)
                    }
                } else {
                    if (is_loggedin == 0) {
                        var cleanPrice = parseFloat((price || '0').toString().replace(/[^\d.-]/g, ''));

                        if (isNaN(cleanPrice) || cleanPrice <= 0) {
                            Toast.fire({
                                icon: 'error',
                                title: 'Invalid price. Please try again.'
                            })
                            return false;
                        }

                        Toast.fire({
                            icon: 'success',
                            title: 'Item added to cart'
                        })

                        var cart_item = {
                            product_variant_id: product_variant_id.trim(),
                            name: title,
                            short_description: description,
                            qty: parseInt(min) || 1,
                            image: image,
                            price: cleanPrice,
                            variant_values: variant_values,
                            min: parseInt(min) || 1,
                            max: parseInt(max) || 100,
                            step: parseInt(step) || 1
                        }


                        var cart = localStorage.getItem('cart')
                        cart =
                            localStorage.getItem('cart') !== null ? JSON.parse(cart) : null

                        var itemExists = false;
                        if (cart !== null && cart !== undefined) {
                            for (var i = 0; i < cart.length; i++) {
                                if (cart[i].product_variant_id == product_variant_id.trim()) {
                                    cart[i].qty = parseInt(cart[i].qty) + parseInt(min);
                                    itemExists = true;
                                    break;
                                }
                            }
                            if (!itemExists) {
                                cart.push(cart_item);
                            }
                        } else {
                            cart = [cart_item]
                        }
                        localStorage.setItem('cart', JSON.stringify(cart))
                        display_cart(cart)
                        return false
                    }
                    Toast.fire({
                        icon: 'error',
                        title: result.message
                    })
                }
            }
        })
    }
})

$(document).ready(function () {
    if (is_loggedin == 0) {
        var cart = localStorage.getItem('cart')
        cart = localStorage.getItem('cart') !== null ? JSON.parse(cart) : null
        if (cart) {
            display_cart(cart)
        }
    }
})

function display_cart(cart) {

    if (cart !== null && cart.length > 0) {
        var cart_count = cart.length ? cart.length : ''
        $('#cart-count').text(cart_count)
        var html = ''
        var validCart = [];

        cart.forEach(item => {
            var priceValue = item.special_price || item.price || 0;
            if (typeof priceValue === 'string') {
                priceValue = priceValue.replace(/[^\d.-]/g, '');
            }
            var itemPrice = parseFloat(priceValue);
            var itemMax = item.max || item.total_allowed_quantity || 999;
            var itemMin = item.min || item.minimum_order_quantity || 1;
            var itemStep = item.step || item.quantity_step_size || 1;
            var itemQty = parseFloat(item.qty || 1);

            if (isNaN(itemPrice) || itemPrice <= 0) {
                console.warn('Skipping item with invalid price:', item);
                return;
            }

            if (is_loggedin == 0) {
                item.price = itemPrice;
                delete item.special_price;
            }

            validCart.push(item);

            if (is_loggedin == 1) {
                item.image = base_url + item.image;
            }

            var variantHtml = '';

            if (is_loggedin == 1 && item.product_variants && item.product_variants.length > 0) {
                if (item.product_variants[0] && item.product_variants[0].variant_values && item.product_variants[0].variant_values !== '') {
                    variantHtml = '<span class="d-block text-muted small">' + item.product_variants[0].variant_values.replace(/,/g, ' | ') + '</span>';
                }
            }
            else if (is_loggedin == 0 && item.variant_values && item.variant_values !== '' && item.variant_values !== 'undefined') {
                variantHtml = '<span class="d-block text-muted small">' + item.variant_values.replace(/,/g, ' | ') + '</span>';
            }

            html +=
                '<div class="row">' +
                '<div class="cart-product product-sm col-md-12">' +
                '<div class="product-image">' +
                '<img class="pic-1" src="' +
                item.image +
                '" alt="Not Found">' +
                '</div>' +
                '<div class="product-details">' +
                '<div class="product-title">' +
                item.name +
                '</div>' +
                variantHtml +
                '<p class="product-descriptions">' +
                item.short_description +
                '</p>' +
                '</div>' +
                '<div class="product-pricing d-flex py-2 px-1 w-100">' +
                '<div class="product-price align-self-center">' +
                currency +
                ' ' +
                itemPrice.toFixed(2) +
                '</div>' +
                '<div class="product-sm-quantity px-1">' +
                '<input type="number" class="form-input"  value="' +
                itemQty +
                '"  data-id="' +
                item.product_variant_id +
                '" data-price="' +
                itemPrice +
                '" min="' +
                itemMin +
                '" max="' +
                itemMax +
                '" step="' +
                itemStep +
                '">' +
                '</div>' +
                '<div class="product-sm-removal align-self-center">' +
                '<button class="remove-product button button-danger" data-id="' +
                item.product_variant_id +
                '">' +
                '<i class="fa fa-trash"></i>' +
                '</button>' +
                '</div>' +
                '<div class="product-line-price align-self-center px-1">' +
                currency +
                ' ' +
                (itemQty * itemPrice).toLocaleString(undefined, {
                    minimumFractionDigits: 2
                }) +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>'
        })

        if (is_loggedin == 0 && validCart.length !== cart.length && validCart.length > 0) {
            localStorage.setItem('cart', JSON.stringify(validCart));
            $('#cart-count').text(validCart.length);
        } else if (is_loggedin == 0 && validCart.length === 0) {
            localStorage.removeItem('cart');
            $('#cart-count').text('');
            $('#cart-item-sidebar').html('<h1 class="h4 text-center">Your Cart Is Empty</h1>');
            return;
        }
    }
    $('#cart-item-sidebar').html(html)

}

function cart_sync() {
    var cart = localStorage.getItem('cart')
    if (cart == null || !cart) {
        return Promise.resolve()
    }

    // Parse and clean the cart data before sending
    try {
        var cartData = JSON.parse(cart);
        // Clean price values - remove currency symbols and ensure numeric
        cartData = cartData.map(function (item) {
            var cleanedItem = Object.assign({}, item);
            // Clean price field
            if (typeof cleanedItem.price === 'string') {
                cleanedItem.price = parseFloat(cleanedItem.price.replace(/[^\d.-]/g, ''));
            }
            // Ensure numeric fields are numbers
            cleanedItem.qty = parseInt(cleanedItem.qty) || 1;
            cleanedItem.min = parseInt(cleanedItem.min) || 1;
            cleanedItem.max = parseInt(cleanedItem.max) || 100;
            cleanedItem.step = parseInt(cleanedItem.step) || 1;
            return cleanedItem;
        });
        cart = JSON.stringify(cartData);
    } catch (e) {
        console.error('Error parsing cart data:', e);
        return Promise.reject('Invalid cart data');
    }

    return $.ajax({
        type: 'POST',
        url: base_url + 'cart/cart_sync',
        data: {
            [csrfName]: csrfHash,
            data: cart,
            is_saved_for_later: false
        },
        dataType: 'json',
        success: function (result) {
            if (typeof result.csrfHash !== 'undefined') {
                csrfHash = result.csrfHash;
            }
            if (result.error == false) {
                // Toast.fire({
                //     icon: 'success',
                //     title: result.message
                // })
                localStorage.removeItem('cart')
                // Update cart count to 0 after successful sync
                $('#cart-count').text('');
            } else {
                // Toast.fire({
                //     icon: 'error',
                //     title: result.message || 'Failed to sync cart'
                // })
            }
        },
        error: function (xhr, status, error) {
            console.error('Cart sync error:', error);
            console.error('Response:', xhr.responseText);
            Toast.fire({
                icon: 'error',
                title: 'Failed to sync cart. Please try again.'
            })
        }
    })
}

$(document).ready(function () {

    $(document).on('click', '#clear_cart', function () {
        if (confirm('Are you sure want to Clear Cart?')) {
            $.ajax({
                type: 'POST',
                data: {
                    [csrfName]: csrfHash
                },
                url: base_url + 'cart/clear',
                dataType: 'json',
                success: function (result) {

                    csrfName = result.csrfName;
                    csrfHash = result.csrfHash;

                    // ✅ Hide cart table
                    $('#cart_item_table').hide();

                    // ✅ Show empty cart image
                    $('#empty-cart').removeClass('d-none');
                }
            });
        }
    });

    $(document).on('click', '#checkout', function (e) {
        if (!confirm('Are You Sure want to Checkout?')) {
            e.preventDefault();
        }
    });

});


$('.quick-view-btn').on('click', function () {
    $('#quick-view').data('data-product-id', $(this).data('productId'))
})
$('.save-for-later').on('click', function (e) {
    e.preventDefault()
    var formdata = new FormData()
    var product_variant_id = $(this).data('id')
    var qty = $(this).parent().siblings('.item-quantity').find('.itemQty').val()
    var product = $(this)
    formdata.append(csrfName, csrfHash)
    formdata.append('product_variant_id', product_variant_id)
    formdata.append('is_saved_for_later', 1)
    formdata.append('qty', qty)
    $.ajax({
        type: 'POST',
        url: base_url + 'cart/manage',
        data: formdata,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (result) {
            if (typeof result.csrfHash !== 'undefined') {
                csrfHash = result.csrfHash;
            }
            if (result.error == false) {
                window.location.reload()
            } else {
                Toast.fire({
                    icon: 'error',
                    title: result.message
                })
            }
        }
    })
})

$('.move-to-cart').on('click', function (e) {
    e.preventDefault()
    var formdata = new FormData()
    var product_variant_id = $(this).data('id')
    var qty = $(this).parent().parent().siblings('.itemQty').text()
    var product = $(this)
    formdata.append(csrfName, csrfHash)
    formdata.append('product_variant_id', product_variant_id)
    formdata.append('is_saved_for_later', 0)
    formdata.append('qty', qty)
    $.ajax({
        type: 'POST',
        url: base_url + 'cart/manage',
        data: formdata,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (result) {
            if (typeof result.csrfHash !== 'undefined') {
                csrfHash = result.csrfHash;
            }
            if (result.error == false) {
                window.location.reload()
            } else {
                Toast.fire({
                    icon: 'error',
                    title: result.message
                })
            }
        }
    })
})

$(document).ready(function () {
    if (localStorage.getItem('compare')) {
        var compare = localStorage.getItem('compare').length
        compare = compare !== null ? JSON.parse(compare) : null
        if (compare) {
            display_compare()
        }
    }
})
$(document).on('click', '.compare', function (e) {
    e.preventDefault()
    var product_id = $(this).attr('data-product-id')
    var product_variant_id = $(this).attr('data-product-variant-id')
    var compare_item = {
        product_id: product_id.trim(),
        product_variant_id: product_variant_id.trim()
    }
    var compare = localStorage.getItem('compare')
    Toast.fire({
        icon: 'success',
        title: 'Added Successfully to Compare'
    })
    compare = compare !== null ? JSON.parse(compare) : null
    if (compare !== null && compare !== undefined) {
        if (compare.find(item => item.product_id === product_id)) {
            Toast.fire({
                icon: 'error',
                title: 'This item is already present in your compare'
            })
            return
        }
        compare.push(compare_item)
    } else {
        compare = [compare_item]
    }
    localStorage.setItem('compare', JSON.stringify(compare))
    var compare_count = compare.length ? compare.length : ''
    $('#compare_count').text(compare_count)
    if (compare !== null && compare_count <= 1) {
        Toast.fire({
            icon: 'error',
            title: 'Please select 1 more item compare'
        })
        return false
    }
})

function display_compare() {
    var compare = localStorage.getItem('compare')
    compare = localStorage.getItem('compare') !== null ? compare : null
    $.ajax({
        type: 'POST',
        url: base_url + 'compare/add_to_compare',
        data: {
            product_id: compare,
            product_variant_id: compare,
            [csrfName]: csrfHash
        },
        dataType: 'json',
        success: function (result) {
            csrfName = result.csrfName
            csrfHash = result.csrfHash
            var compare_count = compare.length ? compare.length : 'base_url()'
            $('#compare_count').text(result.data.total)
            var comp = ''
            if (result.error == false) {
                if (compare !== null && compare_count > 0) {
                    comp +=
                        '<div class="text-right">' +
                        '<div class="compare-removal"><button class="remove-compare button button-danger" >Clear Compare</button></div></div>' +
                        '</div>' +
                        '<table class="compare-table mt-4">' +
                        '<tbody>' +
                        '<tr>' +
                        '<th class="compare-field"> </th>'
                    $.each(result.data.product, function (i, e) {
                        var variant_price =
                            e.variants[0]['special_price'] > 0 &&
                                e.variants[0]['special_price'] != '' ?
                                e.variants[0]['special_price'] :
                                e.variants[0]['price']
                        var data_min = e.minimum_order_quantity ?
                            e.minimum_order_quantity :
                            1
                        var data_step =
                            e.minimum_order_quantity && e.quantity_step_size ?
                                e.quantity_step_size :
                                1
                        var data_max = e.total_allowed_quantity ?
                            e.total_allowed_quantity :
                            1
                        comp +=
                            '<td class="compare_item text-center text-justify">' +
                            '<div class="text-right"><a class="remove-compare-item"' +
                            'data-product-id="' +
                            e.id +
                            '" style="padding: 4px 8px border:0px !important" >' +
                            '<i class="fa-times fa-times-plus fa-lg fa link-color"></i></a></div><br>' +
                            '<div class="product-grid" style="border:1px !important; padding:0 0 0px;"><div class="product-image"><div class="product-image-container"><a href="products/details/' +
                            e.slug +
                            '"><img class="pic-1" src="' +
                            e.image +
                            '"></a></div></div><div itemscope itemtype="https://schema.org/Product">'
                        if (e.rating && e.no_of_rating != '') {
                            comp +=
                                '<div class="col-md-12 mb-3 product-rating-small" dir="ltr" itemprop="aggregateRating" itemscope itemtype="https://schema.org/AggregateRating"><meta itemprop="reviewCount" content="' +
                                e.no_of_rating +
                                '" /><meta itemprop="ratingValue" content="' +
                                e.rating +
                                '" /><input type="text" class="kv-fa rating-loading" value="' +
                                e.rating +
                                '" data-size="sm" title="" readonly> <span class="my-auto mx-3"> ( ' +
                                e.no_of_ratings +
                                ' reviews) </span></div>'
                        } else {
                            comp +=
                                '<div class="col-md-12 mb-3 product-rating-small" dir="ltr"><input type="text" class="kv-fa rating-loading" value="' +
                                e.rating +
                                '" data-size="sm" title="" readonly> <span class="my-auto mx-3"> ( ' +
                                e.no_of_ratings +
                                ' reviews) </span></div>'
                        }

                        comp += '</div>'
                        comp +=
                            ' <h3 class="data-product-title" ><a href="products/details/' +
                            e.slug +
                            '">' +
                            shortDescriptionWordLimit(e.name) +
                            '</a></h3>   <div class="price mb-1">' +
                            currency +
                            ' ' +
                            (e.type == 'simple_product' ?
                                e.variants[0]['price'] :
                                e.min_max_price.max_special_price +
                                ' - ' +
                                e.min_max_price.max_price) +
                            ' </div>'
                        if (e.type == 'simple_product') {
                            var variant_id = e.variants[0]['id']
                            var modal = ''
                        } else {
                            var variant_id = ''
                            var modal = '#quick-view'
                        }
                        comp +=
                            '  <a href="#" class="add-to-cart add_to_cart" data-product-id="' +
                            e.id +
                            '" data-product-variant-id="' +
                            variant_id +
                            '" data-izimodal-open="' +
                            modal +
                            '" data-product-title="' +
                            e.name +
                            '" data-product-image="' +
                            e.image +
                            '" data-product-description="' +
                            e.short_description +
                            '"  data-product-price="' +
                            variant_price +
                            '" data-min="' +
                            data_min +
                            '" data-max="' +
                            data_max +
                            '" data-step="' +
                            data_step +
                            '"><i class="fas fa-cart-plus"></i> Add to Cart</a>';
                        ('</td>')
                    })
                    comp += '</tr>'
                    comp +=
                        '<tr>' +
                        '<th class="compare-field text-center text-justify">Description </th>'
                    $.each(result.data.product, function (i, e) {
                        comp +=
                            '<td class="text-center text-justify" data-title="Availability">' +
                            (e.short_description ?
                                e.short_description :
                                (e.short_description = '-')) +
                            '</td>'
                    })
                    comp += '</tr>'
                    comp +=
                        '<tr>' +
                        '<th class="compare-field text-center text-justify">variants </th>'
                    $.each(result.data.product, function (i, e) {
                        var attribute_name = e.variants[0]['attr_name'].split(',')
                        var attribute_values = e.variants[0]['variant_values'].split(',')
                        if (e.type == 'variable_product') {
                            comp +=
                                '<td class="text-center text-justify" data-title="variants">'
                            for (var i = 0; i < attribute_name.length; i++) {
                                if (attribute_name[i] !== attribute_values[i]) {
                                    comp +=
                                        attribute_name[i] + ' : ' + attribute_values[i] + '<br>'
                                }
                            }
                            comp += '</td>'
                        } else {
                            comp +=
                                '<td class="text-center text-justify" data-title="variants">-</td>'
                        }
                    })
                    comp += '</tr>'
                    comp +=
                        '<tr>' +
                        '<th class="compare-field text-center text-justify">Availability </th>'
                    $.each(result.data.product, function (i, e) {
                        comp +=
                            '<td class="text-center text-justify" data-title="Availability">' +
                            (e.availability == '0' ?
                                (e.availability = 'Out of Stock') :
                                (e.availability = 'In Stock')) +
                            '</td>'
                    })
                    comp += '</tr>'
                    comp +=
                        '<tr>' +
                        '<th class="compare-field text-center text-justify">Made In </th>'
                    $.each(result.data.product, function (i, e) {
                        comp +=
                            '<td class="text-center text-justify" data-title="made in">' +
                            (e.made_in ? e.made_in : '-') +
                            '</td>'
                    })
                    comp += '</tr>'
                    comp +=
                        '<tr>' +
                        '<th class="compare-field text-center text-justify">Warranty</th>'
                    $.each(result.data.product, function (i, e) {
                        comp +=
                            '<td class="text-center text-justify" data-title="warranty period">' +
                            (e.warranty_period ? e.warranty_period : '-') +
                            '</td>'
                    })
                    comp += '</tr>'
                    comp +=
                        '<tr>' +
                        '<th class="compare-field text-center text-justify">Guarantee</th>'
                    $.each(result.data.product, function (i, e) {
                        comp +=
                            '<td class="text-center text-justify" data-title="warranty period">' +
                            (e.guarantee_period ? e.guarantee_period : '-') +
                            '</td>'
                    })
                    comp += '</tr>'
                    comp +=
                        '<tr>' +
                        '<th class="compare-field text-center text-justify">Returnable</th>'
                    $.each(result.data.product, function (i, e) {
                        comp +=
                            '<td class="text-center text-justify" data-title="Returnable">' +
                            (e.is_returnable == '1' ?
                                (e.is_returnable = 'Yes') :
                                (e.is_returnable = 'No')) +
                            '</td>'
                    })
                    comp += '</tr>'
                    comp +=
                        '<tr>' +
                        '<th class="compare-field text-center text-justify">Cancelable</th>'
                    $.each(result.data.product, function (i, e) {
                        comp +=
                            '<td class="text-center text-justify" data-title="cancelable">' +
                            (e.is_cancelable == '1' ?
                                (e.is_cancelable = 'Yes') :
                                (e.is_cancelable = 'No')) +
                            '</td>'
                    })
                    comp += '</tr>'
                    comp += '</tbody>' + '</table>'
                }
                $('#compare-items').html(comp)
                $('.kv-fa').rating({
                    theme: 'krajee-fa',
                    filledStar: '<i class="fas fa-star"></i>',
                    emptyStar: '<i class="far fa-star"></i>',
                    showClear: false,
                    showCaption: false,
                    size: 'md'
                })
            } else {
                Toast.fire({
                    icon: 'error',
                    title: result.message
                })
            }
        }
    })
}
//Remove from compare item.
$(document).on('click', '.remove-compare-item', function (e) {
    e.preventDefault()
    var product_id = $(this).attr('data-product-id')
    if (confirm('Are you sure want to remove this?')) {
        var compare_count = $('#compare_count').text()
        compare_count--
        $('#compare_count').text(compare_count)
        if (compare_count < 1) {
            $(this).parent().parent().remove()
            //   location.reload()
        } else {
            $(this).parent().parent().remove()
        }
        var compare = localStorage.getItem('compare')
        compare = compare !== null ? JSON.parse(compare) : null
        if (compare) {
            var new_compare = compare.filter(function (item) {
                return item.product_id != product_id
            })
            localStorage.setItem('compare', JSON.stringify(new_compare))
            display_compare()
        }
    }
})
// Clear from compare item.
$(document).on('click', '.compare-removal button', function (e) {
    e.preventDefault()
    var id = $(this).attr('data-product-id')
    var compare = $(this).parent().parent().parent()
    if (confirm('Are you sure want to remove this?')) {
        localStorage.removeItem('compare')
        var compare = localStorage.getItem('compare')
        compare =
            localStorage.getItem('compare') !== null ? JSON.parse(compare) : null
        if (compare) {
            var new_compare = compare.filter(function (item) {
                return item.id != id
            })
            localStorage.setItem('compare', JSON.stringify(new_compare))
            if (compare) display_compare(new_compare)
        }

        setTimeout(function () {
            location.reload()
        }, 1000)
    }
})


function shortDescriptionWordLimit(string, length = 12, dots = "...") {
    return (string.length > length) ? string.substring(0, length - dots.length) + dots : string;
}

$('.update-order-item').on('click', function (e) {
    e.preventDefault()
    var formdata = new FormData()
    var order_item_id = $(this).data('item-id')
    var status = $(this).data('status')
    var t = $(this)
    var btn_text = t.text()
    formdata.append(csrfName, csrfHash)
    formdata.append('order_item_id', order_item_id)
    formdata.append('status', status)
    $.ajax({
        type: 'POST',
        url: base_url + 'my-account/update-order-item-status',
        data: formdata,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        beforeSend: function () {
            t.html('Please Wait').attr('disabled', true)
        },
        success: function (result) {

            csrfName = result.csrfName
            csrfHash = result.csrfHash
            if (result.error == false) {
                Toast.fire({
                    icon: 'success',
                    title: result.message
                })

                setTimeout(function () {
                    location.reload()
                }, 1000)
            } else {
                Toast.fire({
                    icon: 'error',
                    title: result.message
                })
            }
            t.html(btn_text).attr('disabled', false)
        }
    })
})

$(document).on('click', '.update-order-item', function (e) {
    e.preventDefault();

    const otherReasonRadio = document.getElementById("otherReasonRadio");
    const otherReasonField = document.getElementById("otherReasonField");
    const reasonRadios = document.querySelectorAll(".reason-radio");

    reasonRadios.forEach(radio => {
        radio.addEventListener("change", function () {

            if (this.value === "other") {
                otherReasonField.style.display = "block";
                otherReasonField.focus(); // Auto-focus the input field
            } else {
                otherReasonField.style.display = "none";
            }
        });
    });
})

$(document).on('click', '.confirmReturn', function (e) {
    e.preventDefault();
    let itemId = $("#returnItemId").val();
    let status = $("#status").val();
    let selectedReason = $("input[name='return_reason']:checked").val();
    let otherReason = $("#otherReasonField").val();
    // let returnImage = $("#return_item_image")[0].files[0]; // Get selected image file
    let returnImage = $("#return_item_image")[0].files; // Get selected image file


    if (!selectedReason) {
        alert("Please select a return reason.");
        return;
    }

    let formData = new FormData();
    formData.append("order_item_id", itemId);
    formData.append("return_reason", selectedReason);
    formData.append("status", status);
    if (selectedReason === "other") {
        formData.append("other_reason", otherReason);
    }
    // Append multiple images
    if (returnImage.length > 0) {

        for (let i = 0; i < returnImage.length; i++) {
            formData.append("return_item_images[]", returnImage[i]);
        }
    }

    formData.append(csrfName, csrfHash);

    $.ajax({
        type: "POST",
        url: base_url + "my-account/update-order-item-status",
        data: formData,
        cache: !1,
        contentType: !1,
        processData: !1,
        dataType: "json",
        beforeSend: function () {
            $("#confirmReturn").prop("disabled", true).text("Processing...");
        },
        success: function (e) {

            csrfName = e.csrfName, csrfHash = e.csrfHash, 0 == e.error ? (Toast.fire({
                icon: "success",
                title: e.message
            }), setTimeout(function () {
                window.location.reload()
            }, 3e3)) : Toast.fire({
                icon: "error",
                title: e.message
            })
            $("#confirmReturn").prop("disabled", false).text("Confirm Return");
        }
    })
}),

    $('.update-order').on('click', function (e) {
        e.preventDefault()
        var formdata = new FormData()
        var order_id = $(this).data('order-id')
        var status = $(this).data('status')
        var temp = ''
        if (status == 'cancelled') {
            temp = 'Cancel'
        } else {
            temp = 'Return'
        }
        if (confirm('Are you sure you want to 1234 ' + temp + ' this order ?')) {
            var t = $(this)
            var btn_text = t.text()
            formdata.append(csrfName, csrfHash)
            formdata.append('order_id', order_id)
            formdata.append('status', status)
            $.ajax({
                type: 'POST',
                url: base_url + 'my-account/update-order-item-status',
                data: formdata,
                cache: false,
                contentType: false,
                processData: false,
                dataType: 'json',
                beforeSend: function () {
                    t.html('Please Wait').attr('disabled', true)
                },
                success: function (result) {
                    csrfName = result.csrfName
                    csrfHash = result.csrfHash
                    if (result.error == false) {
                        Toast.fire({
                            icon: 'success',
                            title: result.message
                        })
                        setTimeout(function () {
                            window.location.reload()
                        }, 3000)
                    } else {
                        Toast.fire({
                            icon: 'error',
                            title: result.message
                        })
                    }
                    t.html(btn_text).attr('disabled', false)
                }
            })
        }
    })
$('#add-address-form').on('submit', function (e) {
    e.preventDefault()
    var formdata = new FormData(this)
    var pincode_test = $('#pincode option:selected').text();
    formdata.append(csrfName, csrfHash);
    formdata.append('pincode_full', pincode_test);
    $.ajax({
        type: 'POST',
        data: formdata,
        url: $(this).attr('action'),
        dataType: 'json',
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function () {
            $('#save-address-submit-btn').val('Please Wait...').attr('disabled', true)
        },
        success: function (result) {
            csrfName = result.csrfName
            csrfHash = result.csrfHash
            if (result.error == false) {
                $('#save-address-result')
                    .html("<div class='alert alert-success'>" + result.message + '</div>')
                    .delay(1500)
                    .fadeOut()
                $('#add-address-form')[0].reset()
                $('#address_list_table').bootstrapTable('refresh')
            } else {
                $('#save-address-result')
                    .html("<div class='alert alert-danger'>" + result.message + '</div>')
                    .delay(1500)
                    .fadeOut()
            }
            $('#save-address-submit-btn').val('Save').attr('disabled', false)
        }
    })
})

$("#city").select2({
    ajax: {
        url: base_url + 'my-account/get_cities',
        type: "GET",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                search: params.term, // search term
            };
        },
        processResults: function (response) {
            return {
                results: response
            };
        },
        cache: true
    },

    minimumInputLength: 1,
    theme: 'bootstrap4',
    placeholder: 'Search for cities',
    // Set the predefined options as selected

})
$('#city').on('change', function (e) {
    e.preventDefault();
    var value = $(this).val()
    if (value == 0 || value == -1) {
        $('.city_name').removeClass('d-none')
        $('.area_name').removeClass('d-none')
        $('.pincode_name').removeClass('d-none')
        $('.area').addClass('d-none')
        $('.pincode').addClass('d-none')
    } else {
        $('#edit_pincode').empty()

        $('.city').trigger('change')

        $('.city').removeClass('d-none')
        $('.area').removeClass('d-none')
        $('.pincode').removeClass('d-none')
        $('.city_name').addClass('d-none')
        $('.area_name').addClass('d-none')
        $('.pincode_name').addClass('d-none')

        $.ajax({

            type: 'POST',

            data: {

                'city_id': $(this).val(),

                [csrfName]: csrfHash,

            },

            url: base_url + 'my-account/get-zipcode',

            dataType: 'json',

            success: function (result) {

                csrfName = result.csrfName;

                csrfHash = result.csrfHash;

                if (result.error == false) {

                    var html = '';

                    html += '<option value="">--Select Zipcode--</option>';
                    html += '<option value="0">Other</option>';

                    $.each(result.data, function (i, e) {

                        html += '<option value=' + e.zipcode + '>' + e.zipcode + '</option>';

                    });

                    $('#pincode').html(html);

                } else {
                    var html = '';
                    html += '<option value="">--Select Zipcode--</option>';
                    html += '<option value="0">Other</option>';

                    $('#pincode').html(html);
                }

            }

        })
    }

});
$('#pincode').on('change', function (e) {
    e.preventDefault();
    var value = $(this).val()
    if (value == 0 || value == -1) {
        $('.pincode_name').removeClass('d-none')
    } else {
        $('.pincode_name').addClass('d-none')
    }
});
$('#edit_pincode').on('change', function (e) {
    e.preventDefault();
    var value = $(this).val()
    if (value == 0 || value == -1) {
        $('.other_pincode').removeClass('d-none')
    } else {
        $('.other_pincode').addClass('d-none')
    }
});

$('#edit-address-form').on('submit', function (e) {
    e.preventDefault()
    var formdata = new FormData(this)
    formdata.append(csrfName, csrfHash)
    $.ajax({
        type: 'POST',
        data: formdata,
        url: $(this).attr('action'),
        dataType: 'json',
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function () {
            $('#edit-address-submit-btn').val('Please Wait...').attr('disabled', true)
        },
        success: function (result) {
            csrfName = result.csrfName
            csrfHash = result.csrfHash
            if (result.error == false) {
                $('#edit-address-result')
                    .html("<div class='alert alert-success'>" + result.message + '</div>')
                    .delay(1500)
                    .fadeOut()
                $('#edit-address-form')[0].reset()
                $('#address_list_table').bootstrapTable('refresh')
                setTimeout(function () {
                    $('#address-modal').modal('hide')
                }, 2000)
            } else {
                $('#edit-address-result')
                    .html("<div class='alert alert-danger'>" + result.message + '</div>')
                    .delay(1500)
                    .fadeOut()
            }
            $('#edit-address-submit-btn').val('Save').attr('disabled', false)
        }
    })
})
$(document).on('click', '.delete-address', function (e) {
    e.preventDefault()
    if (confirm('Are you sure ? You want to delete this address?')) {
        $.ajax({
            type: 'POST',
            data: {
                id: $(this).data('id'),
                [csrfName]: csrfHash
            },
            url: base_url + 'my-account/delete-address',
            dataType: 'json',
            success: function (result) {
                csrfName = result.csrfName
                csrfHash = result.csrfHash
                if (result.error == false) {
                    $('#address_list_table').bootstrapTable('refresh')
                } else {
                    Toast.fire({
                        icon: 'error',
                        title: result.message
                    })
                }
            }
        })
    }
})

$(document).on('click', '.default-address', function (e) {
    e.preventDefault()
    if (confirm('Are you sure ? You want to set this address as default?')) {
        $.ajax({
            type: 'POST',
            data: {
                id: $(this).data('id'),
                [csrfName]: csrfHash
            },
            url: base_url + 'my-account/set-default-address',
            dataType: 'json',
            success: function (result) {
                csrfName = result.csrfName
                csrfHash = result.csrfHash
                if (result.error == false) {
                    $('#address_list_table').bootstrapTable('refresh')
                    Toast.fire({
                        icon: 'success',
                        title: result.message
                    })
                } else {
                    Toast.fire({
                        icon: 'error',
                        title: result.message
                    })
                }
            }
        })
    }
})

$(document).on('click', '#forgot_password_link', function (e) {
    e.preventDefault()
    $('.auth-modal').find('header a').removeClass('active')
    $('#forgot_password_div')
        .removeClass('hide')
        .siblings('section')
        .addClass('hide')
    $('#recaptcha-container-2').html('')
    window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
        'recaptcha-container-2'
    )
    window.recaptchaVerifier.render().then(function (widgetId) {
        grecaptcha.reset(widgetId)
    })
    var telInput = $('#forgot_password_number')
    // initialise plugin
    telInput.intlTelInput({
        allowExtensions: true,
        formatOnDisplay: true,
        autoFormat: true,
        autoHideDialCode: true,
        autoPlaceholder: true,
        defaultCountry: 'in',
        ipinfoToken: 'yolo',

        nationalMode: false,
        numberType: 'MOBILE',
        preferredCountries: ['in', 'ae', 'qa', 'om', 'bh', 'kw', 'ma'],
        preventInvalidNumbers: true,
        separateDialCode: true,
        initialCountry: 'auto',
        geoIpLookup: function (callback) {
            $.get('https://ipinfo.io', function () { }, 'jsonp').always(function (
                resp
            ) {
                var countryCode = resp && resp.country ? resp.country : ''
                callback(countryCode)
            })
        },
        utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.15/js/utils.js'
    })
})

$(document).on('submit', '#send_forgot_password_otp_form', function (e) {
    e.preventDefault()
    var send_otp_btn = $('#forgot_password_send_otp_btn').html()
    $('#forgot_password_send_otp_btn')
        .html('Please Wait...')
        .attr('disabled', true)
    var phoneNumber =
        $('.selected-dial-code').html() + $('#forgot_password_number').val()
    var response = is_user_exist($('#forgot_password_number').val())
    if (response.error == false) {
        $('#forgot_pass_error_box').html(
            'You have not registered using this number.'
        )
        $('#forgot_password_send_otp_btn')
            .html(send_otp_btn)
            .attr('disabled', false)
    } else {
        var appVerifier = window.recaptchaVerifier
        firebase
            .auth()
            .signInWithPhoneNumber(phoneNumber, appVerifier)
            .then(function (confirmationResult) {
                resetRecaptcha()
                $('#verify_forgot_password_otp_form').removeClass('d-none')
                $('#send_forgot_password_otp_form').hide()
                $('#forgot_pass_error_box').html(response.message)
                $('#forgot_password_send_otp_btn')
                    .html(send_otp_btn)
                    .attr('disabled', false)
                $(document).on('submit', '#verify_forgot_password_otp_form', function (e) {
                    e.preventDefault()
                    var reset_pass_btn_html = $('#reset_password_submit_btn').html()
                    var code = $('#forgot_password_otp').val()
                    var formdata = new FormData(this)
                    var url = base_url + 'home/reset-password'
                    $('#reset_password_submit_btn')
                        .html('Please Wait...')
                        .attr('disabled', true)
                    confirmationResult
                        .confirm(code)
                        .then(function (result) {
                            formdata.append(csrfName, csrfHash)
                            formdata.append('mobile', $('#forgot_password_number').val())
                            $.ajax({
                                type: 'POST',
                                url: url,
                                data: formdata,
                                processData: false,
                                contentType: false,
                                cache: false,
                                dataType: 'json',
                                beforeSend: function () {
                                    $('#reset_password_submit_btn')
                                        .html('Please Wait...')
                                        .attr('disabled', true)
                                },
                                success: function (result) {
                                    csrfName = result.csrfName
                                    csrfHash = result.csrfHash
                                    $('#reset_password_submit_btn')
                                        .html(reset_pass_btn_html)
                                        .attr('disabled', false)
                                    $('#set_password_error_box').html(result.message).show()
                                    if (result.error == false) {
                                        setTimeout(function () {
                                            window.location.reload()
                                        }, 2000)
                                    }
                                }
                            })
                        })
                        .catch(function (error) {
                            $('#reset_password_submit_btn')
                                .html(reset_pass_btn_html)
                                .attr('disabled', false)
                            $('#set_password_error_box')
                                .html('Invalid OTP. Please Enter Valid OTP')
                                .show()
                        })
                }
                )
            })
            .catch(function (error) {
                $('#forgot_pass_error_box').html(error.message).show()
                $('#forgot_password_send_otp_btn')
                    .html(send_otp_btn)
                    .attr('disabled', false)
                resetRecaptcha()
            })
    }
})

function transaction_query_params(p) {
    return {
        transaction_type: 'transaction',
        user_id: $('#transaction_user_id').val(),
        limit: p.limit,
        sort: p.sort,
        order: p.order,
        offset: p.offset,
        search: p.search
    }
}

function customer_wallet_query_params(p) {
    return {
        transaction_type: 'wallet',
        limit: p.limit,
        sort: p.sort,
        order: p.order,
        offset: p.offset,
        search: p.search
    }
}

function customer_withdrawal_query_params(p) {
    return {

        limit: p.limit,
        offset: p.offset,
    }
}

$('#contact-us-form').on('submit', function (e) {
    e.preventDefault()
    var submit_btn_html = $('#contact-us-submit-btn').html()
    var formdata = new FormData(this)
    formdata.append(csrfName, csrfHash)
    $.ajax({
        type: 'POST',
        data: formdata,
        url: $(this).attr('action'),
        dataType: 'json',
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function () {
            $('#contact-us-submit-btn').html('Please Wait...').attr('disabled', true)
        },
        success: function (result) {
            csrfName = result.csrfName
            csrfHash = result.csrfHash
            if (result.error == false) {
                Toast.fire({
                    icon: 'success',
                    title: result.message
                })
                $('#contact-us-form')[0].reset()
            } else {
                Toast.fire({
                    icon: 'error',
                    title: result.message
                })
            }
            $('#contact-us-submit-btn').html(submit_btn_html).attr('disabled', false)
        }
    })
})

$('#product-rating-form').on('submit', function (e) {
    e.preventDefault()
    var submit_btn_html = $('#rating-submit-btn').html()
    var formdata = new FormData(this)
    formdata.append(csrfName, csrfHash)
    $.ajax({
        type: 'POST',
        data: formdata,
        url: $(this).attr('action'),
        dataType: 'json',
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function () {
            $('#rating-submit-btn').html('Please Wait...').attr('disabled', true)
        },
        success: function (result) {
            csrfName = result.csrfName
            csrfHash = result.csrfHash
            if (result.error == false) {
                Toast.fire({
                    icon: 'success',
                    title: result.message
                })
                $('#product-rating-form')[0].reset()
                setTimeout(function () {
                    location.reload()
                }, 1300);
            } else {
                Toast.fire({
                    icon: 'error',
                    title: result.message
                })
                setTimeout(function () {
                    location.reload()
                }, 1300);
            }
            $('#rating-submit-btn').html(submit_btn_html).attr('disabled', false)
        }
    })
})

$(document).on('click', '.delete_rating', function (e) {
    e.preventDefault()
    if (confirm('Are you sure want to Delete Rating ?')) {
        var rating_id = $(this).data('rating-id')
        var deleteButton = $(this)
        $.ajax({
            type: 'POST',
            data: {
                [csrfName]: csrfHash,
                rating_id: rating_id
            },
            url: $(this).attr('href'),
            dataType: 'json',
            success: function (result) {
                csrfName = result['csrfName']
                csrfHash = result['csrfHash']
                if (result.error == false) {
                    Toast.fire({
                        icon: 'success',
                        title: result.message
                    })
                    deleteButton.closest('.review-container').remove()
                    $('#no_ratings').text(result.data.rating[0].no_of_rating)
                } else {
                    Toast.fire({
                        icon: 'error',
                        title: result.message
                    })
                }
            }
        })
    }
})
$('#edit_link').on('click', function (e) {
    e.preventDefault()
    $('#rating-box').removeClass('d-none')
})

$('#load-user-ratings').on('click', function (e) {
    e.preventDefault()
    var limit = $(this).attr('data-limit')
    var offset = $(this).attr('data-offset')
    var product_id = $(this).attr('data-product')
    var btn_html = $(this).html()
    var btn = $(this)
    var html = ''
    $.ajax({
        type: 'GET',
        data: {
            limit: limit,
            offset: offset,
            product_id: product_id
        },
        url: base_url + 'products/get-rating',
        dataType: 'json',
        beforeSend: function () {
            $(this).html('Please wait..').attr('disabled', true)
        },
        success: function (result) {
            $(this).html(btn_html).attr('disabled', false)
            if (result.error == false) {
                $.each(result.data.product_rating, function (i, e) {
                    html +=
                        '<li class="review-container">' +
                        '<div class="review-image">' +
                        '<img src="' +
                        base_url +
                        'assets/front_end/modern/images/user.png" alt="" width="65" height="65">' +
                        '</div>' +
                        '<div class="review-comment">' +
                        '<div class="rating-list">' +
                        '<div class="product-rating">' +
                        '<input type="text" class="kv-fa" value="' +
                        e.rating +
                        '" data-size="xs" title="" readonly>' +
                        '</div>' +
                        '</div>' +
                        '<div class="review-info">' +
                        '<h4 class="reviewer-name">' +
                        e.user_name +
                        '</h4>' +
                        ' <span class="review-date text-muted">' +
                        e.data_added +
                        '</span>' +
                        '</div>' +
                        '<div class="review-text">' +
                        '<p class="text-muted">' +
                        e.comment +
                        '</p>' +
                        '</div>' +
                        '<div class="row reviews">'
                    $.each(e.images, function (j, image) {
                        html +=
                            '<div class="col-md-2">' +
                            '<div class="review-box">' +
                            '<a href="' +
                            image +
                            '" data-lightbox="review-images">' +
                            '<img src="' +
                            image +
                            '" alt="' +
                            image +
                            '">' +
                            '</a>' +
                            '</div>' +
                            '</div>'
                    })

                    html += '</div>' + '</div>' + '</li>'
                })
                offset += limit
                $('#review-list').append(html)
                $('.kv-fa').rating('create', {
                    filledStar: '<i class="fas fa-star"></i>',
                    emptyStar: '<i class="far fa-star"></i>',
                    size: 'xs',
                    showCaption: false
                })
                btn.attr('data-offset', offset)
            } else {
                Toast.fire({
                    icon: 'error',
                    title: result.message
                })
            }
        }
    })
})
$("#edit_city").select2({
    ajax: {
        url: base_url + 'my-account/get_cities',
        type: "GET",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                search: params.term, // search term
            };
        },
        processResults: function (response) {
            return {
                results: response
            };
        },
        cache: true
    },

    minimumInputLength: 1,
    theme: 'bootstrap4',
    placeholder: 'Search for cities',
})
$('#edit_city').on('change', function (e, pincode) {

    e.preventDefault();

    var city_id = $(this).val();
    var value = $(this).val()
    if (value == 0 || value == '') {
        $('.edit_area').addClass('d-none')
        $('#edit_area').val('')
        $('.edit_pincode').addClass('d-none')
        $('.other_city').removeClass('d-none')
        $('.other_areas').removeClass('d-none')
        $('.other_pincode').removeClass('d-none')
    } else {
        $('.edit_area').removeClass('d-none')
        $('.edit_pincode').removeClass('d-none')
        $('.edit_city').removeClass('d-none')
        $('.other_city').addClass('d-none')
        $('.other_areas').addClass('d-none')
        $('.other_pincode').addClass('d-none')

        $.ajax({

            type: 'POST',

            data: {

                'city_id': $(this).val(),

                [csrfName]: csrfHash,

            },

            url: base_url + 'my-account/get-zipcode',

            dataType: 'json',

            success: function (result) {

                csrfName = result.csrfName;

                csrfHash = result.csrfHash;

                if (result.error == false) {

                    var html = '';

                    $.each(result.data, function (i, e) {

                        var is_selected = (e.zipcode == pincode) ? "selected" : "";

                        html += '<option value="0">Other</option>';
                        html += '<option value=' + e.zipcode + ' ' + is_selected + '>' + e.zipcode + '</option>';

                    });

                    $('#edit_pincode').html(html);

                } else {

                    Toast.fire({

                        icon: 'error',

                        title: result.message

                    });

                    $('#edit_pincode').html('');

                }

            }

        })
    }

});

if ($('#product-filters').length) {
    if (!checkUrlHasParam()) {
        sessionStorage.setItem(
            $('#product-filters').data('key'),
            $('#product-filters').val()
        )
        var filters = sessionStorage.getItem($('#product-filters').data('key'))
        filters = filters.replace(/\\/g, '')
        // print_filters(filters, 'Desktop', '#product-filters-desktop')
        // print_filters(filters, 'Mobile', '#product-filters-mobile')
        print_filters_desktop(filters, 'Desktop', '#product-filters-desktop')
        print_filters_mobile(filters, 'Mobile', '#product-filters-mobile')
        print_filters_mobile_value(filters, 'Mobile', '#product-filters-mobile-value')
    } else {
        if (
            sessionStorage.getItem($('#product-filters').data('key')) == undefined
        ) {
            sessionStorage.setItem(
                $('#product-filters').data('key'),
                $('#product-filters').val()
            )
        }
        var filters = sessionStorage.getItem($('#product-filters').data('key'))
        filters = filters.replace(/\\/g, '')
        // print_filters(filters, 'Desktop', '#product-filters-desktop')
        // print_filters(filters, 'Mobile', '#product-filters-mobile')
        print_filters_desktop(filters, 'Desktop', '#product-filters-desktop')
        print_filters_mobile(filters, 'Mobile', '#product-filters-mobile')
        print_filters_mobile_value(filters, 'Mobile', '#product-filters-mobile-value')
    }
}

function print_filters(filters, prefix = '', target) {
    var html = ''
    var attribute_values_id
    var attribute_values
    var new_attr_val
    var attr_name
    var collapse_status
    var selected_attributes
    var attr_checked_status
    var e_name
    if (filters != '') {
        $.each(JSON.parse(filters), function (i, e) {

            const brand_name = getUrlParameter('brand');
            var brands = $('[data-value="' + brand_name + '"]');
            $('[data-value="' + brand_name + '"]').attr('checked');
            var gp = $(brands).siblings();
            $(gp).addClass('selected-brand');

            e_name = e.name.replace(' ', '-').toLowerCase()
            e_name = decodeURIComponent(e_name)
            attr_name = getUrlParameter('filter-' + e_name)
            collapse_status = attr_name == undefined ? ' ' : 'show'
            selected_attributes = attr_name != undefined ? attr_name.split('|') : ''
            html +=
                '<div class="card-custom">' +
                '<div class="card-header-custom" id="h' +
                i +
                '">' +
                '<h2 class="clearfix mb-0">' +
                '<a class="collapse-arrow btn btn-link collapsed" data-toggle="collapse" data-target="#' +
                prefix +
                i +
                '" aria-expanded="true" aria-controls="#' +
                prefix +
                i +
                '">' +
                e.name +
                '<i class="fa fa-angle-down rotate"></i></a>' +
                '</h2>' +
                '</div>' +
                '<div id="' +
                prefix +
                i +
                '" class="collapse ' +
                collapse_status +
                '" aria-labelledby="h' +
                i +
                '" data-parent="#accordionExample">' +
                '<div class="card-body-custom">'
            attribute_values_id = e.attribute_values_id.split(',')
            attribute_values = e.attribute_values.split(',')

            $.each(attribute_values, function (j, v) {
                attr_checked_status =
                    $.inArray(v, selected_attributes) !== -1 ? 'checked' : ''
                new_attr_val = e_name + ' ' + v
                html +=
                    '<div class="input-container d-flex">' +
                    '<input type="checkbox" name="' +
                    v +
                    '" value="' +
                    v +
                    '" class="toggle-input product_attributes" id="' +
                    prefix +
                    new_attr_val +
                    '" data-attribute="' +
                    e_name +
                    '" ' +
                    attr_checked_status +
                    '>' +
                    '<label class="toggle checkbox" for="' +
                    prefix +
                    new_attr_val +
                    '">' +
                    '<div class="toggle-inner"></div>' +
                    '</label>' +
                    '<label for="' +
                    prefix +
                    new_attr_val +
                    '" class="text-label">' +
                    v +
                    '</label></div>'
            })
            html += '</div>' + '</div>' + '</div>'
        })
    }
    $(target).html(html)
}
function print_filters_desktop(filters, prefix = '', target) {
    var html = ''
    var attribute_values_id
    var attribute_values
    var new_attr_val
    var attr_name
    var collapse_status
    var selected_attributes
    var attr_checked_status
    var e_name

    function decodeUnicode(inputStr) {
        return inputStr.replace(/u([0-9A-Fa-f]{4})/g, (match, group) => {
            return String.fromCharCode(parseInt(group, 16));
        });
    }

    if (filters != '') {

        $.each(JSON.parse(filters), function (i, e) {
            const brand_name = getUrlParameter('brand');
            var brands = $('[data-value="' + brand_name + '"]');
            $('[data-value="' + brand_name + '"]').attr('checked');
            var gp = $(brands).siblings();
            $(gp).addClass('selected-brand');

            e_name = decodeUnicode(e.name.replace(' ', '-').toLowerCase());
            attr_name = getUrlParameter('filter-' + e_name);
            collapse_status = attr_name == undefined ? ' ' : 'show';
            selected_attributes = attr_name != undefined ? attr_name.split('|') : '';
            html +=
                '<div class="card-custom">' +
                '<div class="card-header-custom" id="h' + i + '">' +
                '<h2 class="clearfix mb-0">' +
                '<a class="collapse-arrow btn btn-link collapsed" data-toggle="collapse" data-target="#' +
                prefix + i + '" aria-expanded="true" aria-controls="#' +
                prefix + i + '">' +
                decodeUnicode(e.name.replace(' ', '-').toLowerCase()) +
                '<i class="fa fa-angle-down rotate"></i></a>' +
                '</h2>' +
                '</div>' +
                '<div id="' + prefix + i + '" class="collapse ' + collapse_status + '" aria-labelledby="h' + i + '" data-parent="#accordionExample">' +
                '<div class="card-body-custom">';
            attribute_values_id = e.attribute_values_id.split(',');
            attribute_values = e.attribute_values.split(',');

            $.each(attribute_values, function (j, v) {
                let decodedValue = decodeUnicode(v);
                attr_checked_status =
                    $.inArray(decodedValue, selected_attributes) !== -1 ? 'checked' : '';
                new_attr_val = e_name + ' ' + decodedValue;
                html +=
                    '<div class="input-container d-flex">' +
                    '<input type="checkbox" name="' + decodedValue + '" value="' + decodedValue + '" class="toggle-input product_attributes" id="' +
                    prefix + new_attr_val + '" data-attribute="' + e_name + '" ' + attr_checked_status + '>' +
                    '<label class="toggle checkbox" for="' + prefix + new_attr_val + '">' +
                    '<div class="toggle-inner"></div>' +
                    '</label>' +
                    '<label for="' + prefix + new_attr_val + '" class="text-label">' + decodedValue + '</label></div>';
            });
            html += '</div></div></div>';
        });
    }
    $(target).html(html);
}



function print_filters_mobile(filters, prefix = '', target) {
    var html = '';
    function decodeUnicode(inputStr) {
        return inputStr.replace(/u([0-9A-Fa-f]{4})/g, (match, group) => {
            return String.fromCharCode(parseInt(group, 16));
        });
    }

    if (filters) {
        $.each(JSON.parse(filters), function (i, e) {
            const e_name = decodeUnicode(e.name.replace(' ', '-').toLowerCase());
            const attr_name = getUrlParameter('filter-' + e_name);
            const collapse_status = attr_name ? 'show' : '';
            html += `
                <div class="nav flex-column nav-pills" id="${prefix}${i}-tab1" role="tablist" aria-orientation="vertical">
                    <button class="nav-link filter-titles" id="${prefix}${i}-tab" data-bs-toggle="tab" data-bs-target="#${prefix}${i}" type="button" role="tab" aria-controls="${prefix}${i}" aria-selected="true">
                        ${e.name}
                    </button>
                </div>`;
        });
    }
    $(target).html(html);
}

function print_filters_mobile_value(filters, prefix = '', target) {
    var html = '';
    function decodeUnicode(inputStr) {
        return inputStr.replace(/u([0-9A-Fa-f]{4})/g, (match, group) => {
            return String.fromCharCode(parseInt(group, 16));
        });
    }

    if (filters) {
        $.each(JSON.parse(filters), function (i, e) {
            const e_name = decodeUnicode(e.name.replace(' ', '-').toLowerCase());
            const attr_name = getUrlParameter('filter-' + e_name);
            const collapse_status = attr_name ? 'show' : '';
            const selected_attributes = attr_name ? attr_name.split('|') : [];

            html += `
                <div class="tab-pane fade ${collapse_status}" id="${prefix}${i}" role="tabpanel" aria-labelledby="${prefix}${i}-tab" tabindex="0">
                    <div class="form-check">`;

            const attribute_values_id = e.attribute_values_id.split(',');
            const attribute_values = e.attribute_values.split(',');

            $.each(attribute_values, function (j, v) {
                const attr_checked_status = selected_attributes.includes(v) ? 'checked' : '';
                const new_attr_val = `${e_name} ${v}`;
                html += `
                    <label class="form-check-label py-2" for="${prefix}${new_attr_val}">
                        <input type="checkbox" name="${v}" value="${v}" class="toggle-input product_attributes width15px form-check-input" id="${prefix}${new_attr_val}" data-attribute="${e_name}" ${attr_checked_status}>
                        ${v}
                    </label>`;
            });
            html += '</div></div>';
        });
    }
    $(target).html(html);
}

$(document).on('closed', '#quick-view', function (e) {
    $('#modal-product-special-price').html('')
})

window.addEventListener('load', addDarkmodeWidget)
const options = {
    time: '0.5s', // default: '0.3s'
    mixColor: '#fff', // default: '#fff'
    backgroundColor: '#fff', // default: '#fff'
    buttonColorDark: '#100f2c', // default: '#100f2c'
    buttonColorLight: '#fff', // default: '#fff'
    label: '🌕' // default: ' 🌙'
}

function addDarkmodeWidget() {
    new Darkmode(options).showWidget()
}
$(document).ready(function () {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError)
    }

    function showPosition(position) {
        var latitude = position.coords.latitude
        var longitude = position.coords.longitude
        sessionStorage.setItem('latitude', latitude)
        sessionStorage.setItem('longitude', longitude)
    }

    function showError(error) {
        switch (error.code) {
            case error.PERMISSION_DENIED:
                if (sessionStorage.getItem('latitude') !== null) {
                    sessionStorage.removeItem('latitude')
                }
                if (sessionStorage.getItem('longitude') !== null) {
                    sessionStorage.removeItem('longitude')
                }
                break
            case error.POSITION_UNAVAILABLE:
                console.log('Location information is unavailable.')
                break
            case error.TIMEOUT:
                console.log('The request to get user location timed out.')
                break
            case error.UNKNOWN_ERROR:
                console.log('An unknown error occurred.')
                break
        }
    }
})

$('#send_bank_receipt_form').on('submit', function (e) {
    e.preventDefault()
    var formdata = new FormData(this)
    formdata.append(csrfName, csrfHash)

    $.ajax({
        type: 'POST',
        url: $(this).attr('action'),
        data: formdata,
        beforeSend: function () {
            $('#submit_btn').html('Please Wait..').attr('disabled', true)
        },
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (result) {
            csrfHash = result.csrfHash
            $('#submit_btn').html('Send').attr('disabled', false)
            if (result.error == false) {
                $('table').bootstrapTable('refresh')
                Toast.fire({
                    icon: 'success',
                    title: result.message
                })
                setTimeout(() => {
                    location.reload();
                }, 1300);
            } else {
                Toast.fire({
                    icon: 'error',
                    title: result.message
                })
                setTimeout(() => {
                    location.reload();
                }, 1300);
            }
        }
    })
})

$(document).ready(function () {
    if ($('.hrDiv').length) {
        $('.hrDiv p').addClass('hrDiv')
        $('div').css({
            'font-size': '',
            font: ''
        })
    }
})

$('#validate-zipcode-form').on('submit', function (e) {
    e.preventDefault()
    var formdata = new FormData(this)
    formdata.append(csrfName, csrfHash)

    $.ajax({
        type: 'POST',
        url: base_url + 'products/check_zipcode',
        data: formdata,
        beforeSend: function () {
            $('#validate_zipcode').html('Please Wait..').attr('disabled', true)
        },
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (result) {
            csrfHash = result.csrfHash
            $('#validate_zipcode').html('Check Availability').attr('disabled', false)
            if (result.error == false) {
                $('#add_cart').removeAttr('disabled')
                $('#error_box').html(result.message)
            } else {
                $('#add_cart').attr('disabled', 'true')
                $('#error_box').html(result.message)
            }
        }
    })
})

$('#validate-city-form').on('submit', function (e) {
    e.preventDefault()
    var formdata = new FormData(this)
    formdata.append(csrfName, csrfHash)

    $.ajax({
        type: 'POST',
        url: base_url + 'products/check_city',
        data: formdata,
        beforeSend: function () {
            $('#validate_city').html('<div class="spinner-border" role="status">' +
                '<span class="visually-hidden">Loading...</span>' +
                '</div>').attr('disabled', true);
        },
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (result) {
            csrfHash = result.csrfHash
            $('#validate_city').html('Check Availability').attr('disabled', false)
            if (result.error == false) {
                $('#add_cart').removeAttr('disabled')
                $('#error_box').html(result.message)
            } else {
                $('#add_cart').attr('disabled', 'true')
                $('#error_box').html(result.message)
            }
        }
    })
})

$(document).on('submit', '.validate_zipcode_quick_view', function (e) {
    e.preventDefault()
    var formdata = new FormData(this)
    formdata.append(csrfName, csrfHash)

    $.ajax({
        type: 'post',
        url: base_url + 'products/check-zipcode',
        data: formdata,
        beforeSend: function () {
            $('#validate_zipcode').html('Please Wait..').attr('disabled', true)
        },
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (result) {
            csrfHash = result.csrfHash
            $('#validate_zipcode').html('Check Availability').attr('disabled', false)
            if (result.error == false) {
                $('#modal-add-to-cart-button').removeAttr('disabled')
                $('#error_box1').html(result.message)
            } else {
                $('#modal-add-to-cart-button').attr('disabled', 'true')
                $('#error_box1').html(result.message)
            }
        }
    })
})
$('.view_cart_button').click(function () {
    if (is_loggedin == 0) {
        $('#modal-custom').iziModal('open')
        $('#login_div').removeClass('hide')
        $('#login').addClass('active')
        $('#register_div').addClass('hide')
        $('#register').removeClass('active')
        return false
    } else {
        return true
    }
})

$('#view_favorites').click(function () {
    if (is_loggedin == 0) {
        $('#modal-custom').iziModal('open')
        $('#login_div').removeClass('hide')
        $('#login').addClass('active')
        $('#register_div').addClass('hide')
        $('#register').removeClass('active')
        return false
    } else {
        return true
    }
})

function mycartTotal() {
    var cartTotal = 0
    $('#cart_item_table > tbody > tr > .total-price  > .product-line-price').each(
        function (i) {
            cartTotal =
                parseFloat(cartTotal) +
                parseFloat(
                    $(this)
                        .text()
                        .replace(/[^\d\.]/g, '')
                )
        }
    )
    $('#final_total').text(cartTotal.toFixed(2))
}

$(document).on('submit', '#add-faqs', function (e) {
    e.preventDefault()
    var formData = new FormData(this)
    formData.append(csrfName, csrfHash)
    $.ajax({
        type: 'POST',
        url: $(this).attr('action'),
        dataType: 'json',
        data: formData,
        processData: false,
        contentType: false,

        success: function (result) {
            csrfName = result['csrfName']
            csrfHash = result['csrfHash']
            if (result.error == false) {
                Toast.fire({
                    icon: 'success',
                    title: result.message
                })
                $('#add-faqs')[0].reset()
            } else {
                Toast.fire({
                    icon: 'error',
                    title: result.message
                })
            }
            setTimeout(function () {
                location.reload()
            }, 1300)
        }
    })
})

// select 2 js select countries
$('.search_faqs').select2({
    ajax: {
        url: base_url + 'products/get_faqs_data',
        type: 'GET',
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                search: params.term // search term
            }
        },
        processResults: function (response) {
            return {
                results: response
            }
        },
        cache: true
    },
    minimumInputLength: 1,
    theme: 'bootstrap4',
    placeholder: 'Search for faqs'
})

function get_flash_sale_timer(element) {
    const end_date = $(element).text()
    const elementId = $(element).data('value')
    // Update the count down every 1 second
    var x = setInterval(function () {
        var countDownDate = new Date(end_date).getTime()
        var now = new Date().getTime()

        // Find the distance between now and the count down date
        var distance = countDownDate - now

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24))
        var hours = Math.floor(
            (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
        )
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
        var seconds = Math.floor((distance % (1000 * 60)) / 1000)

        var timer = days + 'd ' + hours + 'h ' + minutes + 'm ' + seconds + 's '

        $(`#timer-${elementId}`).text(timer)

        $(`#timer-${elementId}`).addClass('badge-success')

        // If the count down is over, write some text
        if (distance < 0) {
            clearInterval(x)
            $(`#timer-${elementId}`).text('Sale is Expired')
            $(`#timer-${elementId}`).addClass('badge-warning')
        }
    }, 1000)
}



$(document).ready(function () {
    $(document).on('click', '.delete_user_account', function () {

        var mobile = $('#Mobile_number').val();
        var password = $('#password').val();
        $.ajax({
            type: 'POST',
            data: {
                mobile: mobile,
                password: password,
                [csrfName]: csrfHash
            },
            dataType: 'json',
            url: base_url + 'My_account/delete_account',
            success: function (result) {

                csrfName = result['csrfName'];
                csrfHash = result['csrfHash'];
                if (result.error == false) {
                    Toast.fire({
                        icon: 'success',
                        title: result.message
                    })

                    location.replace(base_url);

                } else {
                    Toast.fire({
                        icon: 'error',
                        title: result.message
                    })
                }
            }
        })

    })
})

$(document).ready(function () {
    $(document).on('click', '.delete_social_account', function () {
        var uid = ''
        var session_user_id = document.getElementById("session_user_id").value;
        firebase.auth().onAuthStateChanged((user) => {
            if (user) {
                uid = user.uid
                user.delete().then(function () {
                    $.ajax({
                        type: 'POST',
                        data: {
                            session_user_id: session_user_id,
                            [csrfName]: csrfHash
                        },
                        dataType: 'json',
                        url: base_url + 'My_account/delete_social_account',
                        success: function (result) {

                            csrfName = result['csrfName'];
                            csrfHash = result['csrfHash'];
                            if (result.error == false) {
                                Toast.fire({
                                    icon: 'success',
                                    title: result.message
                                })
                                location.replace(base_url);

                            } else {
                                Toast.fire({
                                    icon: 'error',
                                    title: result.message
                                })
                            }
                        }
                    })


                    var ref = firebase.database().ref(
                        "users/".concat(user.uid, "/")
                    );
                    ref.remove();
                });


            } else {

            }
        });



    })
})

$(document).on('click', '.ticket_button', function (e) {
    $('.display_fields').removeClass('d-none')
})
$(document).on('click', '.edit_button', function (e) {
    $('.hide_table').removeClass('d-none')
})

$(document).on('submit', '#ticket_form', function (e) {
    e.preventDefault(); // ✅ STOP normal form submit

    var subject = $('#subject').val().trim();
    var description = $('#description').val().trim();
    var type = $('#ticket_type').val();
    var email = $('#email').val().trim();
    var id = $('#user_id').val();

    // ✅ Basic frontend validation
    if (!type || !email || !subject || !description) {
        Toast.fire({
            icon: 'error',
            title: 'All fields are required'
        });
        return;
    }

    $.ajax({
        type: 'POST',
        url: base_url + 'Tickets/add_ticket',
        dataType: 'json',
        data: {
            ticket_type_id: type,
            email: email,
            subject: subject,
            description: description,
            user_id: id,
            [csrfName]: csrfHash
        },
        beforeSend: function () {
            $('.ask_question').prop('disabled', true).text('Please wait...');
        },
        success: function (result) {

            csrfName = result.csrfName;
            csrfHash = result.csrfHash;

            if (result.error === false) {
                Toast.fire({
                    icon: 'success',
                    title: result.message || 'Ticket submitted successfully'
                });

                $('#ticket_form')[0].reset();

                setTimeout(function () {
                    location.reload();
                }, 600);

            } else {
                Toast.fire({
                    icon: 'error',
                    title: result.message || 'Validation failed'
                });
            }
        },
        error: function (xhr) {
            let msg = 'Server error';

            if (xhr.responseJSON && xhr.responseJSON.message) {
                msg = xhr.responseJSON.message;
            }

            // Toast.fire({
            //     icon: 'error',
            //     title: msg
            // });
        },
        complete: function () {
            $('.ask_question').prop('disabled', false).text('Save');
        }
    });
});

var ticket_id = $('#edit_id').val();
var user_id = $('#user_id').val();

var scrolled = 0
$(document).ready(function () {
    $(document).on('click', '.update_question', function () {
        var type = $('#ticket_type').val();
        var email = $('#email_id').val();
        var subject = $('#subject_id').val();
        var description = $('#description_id').val();
        var id = $('#user_id').val();
        ticket_id = $('#edit_id').val();



        $.ajax({
            type: 'POST',
            data: {
                ticket_type_id: type,
                email: email,
                edit_id: ticket_id,
                subject: subject,
                description: description,
                user_id: id,
                [csrfName]: csrfHash
            },
            dataType: 'json',
            url: base_url + 'Tickets/update_ticket',
            success: function (result) {

                csrfName = result['csrfName'];
                csrfHash = result['csrfHash'];
                var isError = result.error;
                var successCondition = (isError === false || isError === 0 || isError === '0' || isError === 'false' || !isError);
                if (successCondition) {
                    Toast.fire({
                        icon: 'success',
                        title: result.message || 'Saved successfully'
                    })
                    setTimeout(function () {
                        location.reload()
                    }, 600)
                } else {
                    Toast.fire({
                        icon: 'error',
                        title: result.message || 'Something went wrong'
                    })
                    setTimeout(function () {
                        location.reload()
                    }, 600)
                }
            }
        })

    })
})







$(document).ready(function () {
    if ($('#element').length) {
        $('#element').scrollTop($('#element')[0].scrollHeight)
        $('#element').scroll(function () {
            if ($('#element').scrollTop() == 0) {
                load_messages($('.ticket_msg'), ticket_id)
            }
        })

        $('#element').bind('mousewheel', function (e) {
            if (e.originalEvent.wheelDelta / 120 > 0) {
                if ($('.ticket_msg')[0].scrollHeight < 370 && scrolled == 0) {
                    load_messages($('.ticket_msg'), ticket_id)
                    scrolled = 1
                }
            }
        })
    }
})


function load_messages(element, ticket_id) {
    var limit = element.data('limit')
    var offset = element.data('offset')

    element.data('offset', limit + offset)
    var max_loaded = element.data('max-loaded')
    if (max_loaded == false) {
        var loader =
            '<div class="loader text-center"><img src="' +
            base_url +
            'assets/pre-loader.gif" alt="Loading. please wait.. ." title="Loading. please wait.. ."></div>'
        $.ajax({
            type: 'get',
            data: 'ticket_id=' + ticket_id + '&limit=' + limit + '&offset=' + offset,
            url: base_url + 'tickets/get_ticket_messages',
            beforeSend: function () {
                $('.ticket_msg').prepend(loader)
            },
            dataType: 'json',
            cache: false,
            contentType: false,
            processData: false,
            success: function (result) {
                if (result.error == false) {
                    if (result.error == false && result.data.length > 0) {
                        var messages_html = ''
                        var is_left = ''
                        var is_right = ''
                        var i = 1
                        result.data.reverse().forEach(messages => {
                            var atch_html = ''
                            is_left = messages.user_type == 'user' ? 'left' : 'right'
                            is_right = messages.user_type == 'user' ? 'right' : 'left'
                            if (messages.attachments.length > 0) {
                                messages.attachments.forEach(atch => {
                                    atch_html +=
                                        "<div class='container-fluid image-upload-section'>" +
                                        "<a class='btn btn-danger btn-xs mr-1 mb-1' href='" +
                                        atch.media +
                                        "'  target='_blank' alt='Attachment Not Found'>Attachment " +
                                        i +
                                        '</a>' +
                                        "<div class='col-md-3 col-sm-12 shadow p-3 mb-5 bg-white rounded m-4 text-center grow image d-none'></div>" +
                                        '</div>'
                                    i++
                                })
                            }
                            messages_html +=
                                "<div class='direct-chat-msg " +
                                is_left +
                                "'>" +
                                "<div class='direct-chat-infos clearfix'>" +
                                "<span class='direct-chat-name float-" +
                                is_left +
                                "' id='name'>" +
                                messages.name +
                                '</span>' +
                                "<span class='direct-chat-timestamp float-" +
                                is_left +
                                "' id='last_updated'>" +
                                messages.last_updated +
                                '</span>' +
                                '</div>' +
                                "<div class='direct-chat-text' id='message'>" +
                                messages.message +
                                '</br>' +
                                atch_html +
                                '</div>' +
                                '</div>'
                        })
                        $('.ticket_msg').prepend(messages_html)
                        $('.ticket_msg').find('.loader').remove()
                        $(element).animate({
                            scrollTop: $(element).offset().top
                        })
                    }
                } else {
                    element.data('offset', offset)
                    element.data('max-loaded', true)
                    $('.ticket_msg').find('.loader').remove()
                    $('.ticket_msg').prepend(
                        '<div class="text-center"> <p>You have reached the top most message!</p></div>'
                    )
                }
                $('#element').scrollTop(20) // Scroll alittle way down, to allow user to scroll more
                $(element).text();
                $(element).animate({
                    scrollTop: $(element).offset().top
                })
                return false
            }
        })
    }
}


$('#ticket_send_msg_form').on('submit', function (e) {
    var user_type = $('#user_type').val();
    var user_id = $('#user_id').val();
    var ticket_id = $('#ticket_id').val();
    var message = $('#message_input').val();
    var attachments = $('#upload').val();

    e.preventDefault()
    if (message == "" && attachments == "") {
        Toast.fire({
            icon: 'error',
            title: 'You need to add atleast one image or message'
        })
    } else {

        var formdata = new FormData(this)
        formdata.append(csrfName, csrfHash)
        $.ajax({
            type: 'POST',
            data: formdata,
            url: base_url + 'Tickets/send_message',
            dataType: 'json',
            cache: false,
            contentType: false,
            processData: false,

            success: function (result) {
                csrfName = result.csrfName
                csrfHash = result.csrfHash
                if (result.error == false) {

                    var time = result['data'].last_updated;
                    if (result['data'].attachments[0] !== undefined) {

                        var image = result['data'].attachments[0].media;
                    }

                    var div = $('.msg-body');
                    var ticket_id = $('#ticket_id').val();
                    load_messages(div, ticket_id);
                    var message = $('#message_input').val();
                    var last_added = $('#last_added').val();
                    var li = document.createElement('li')
                    var span = document.createElement('span')

                    var ul = document.getElementById('message-ul');

                    li.setAttribute('class', 'repaly')
                    if (image) {

                        li.innerHTML = `<p><img class="chat-img" src="${image}" alt=""></p></br><span class="time price">${time}</span>`

                    } else {
                        li.innerHTML = `<p>${message}</p></br><span class="time price">${time}</span>`
                    }

                    ul.append(li)
                    document.getElementById("message_input").value = "";
                    document.getElementById("upload").value = "";

                } else {
                    $('#save-address-result')
                        .html("<div class='alert alert-danger'>" + result.message + '</div>')
                        .delay(1500)
                        .fadeOut()
                }
                $('#save-address-submit-btn').val('Save').attr('disabled', false)
            }
        })
    }
})



$(document).ready(function () {
    if ($('#element').length) {
        $('#element').scrollTop($('#element')[0].scrollHeight)
        $('#element').scroll(function () {
            if ($('#element').scrollTop() == 0) {
                load_messages($('.ticket_msg'), ticket_id)
            }
        })

        $('#element').bind('mousewheel', function (e) {
            if (e.originalEvent.wheelDelta / 120 > 0) {
                if ($('.ticket_msg')[0].scrollHeight < 370 && scrolled == 0) {
                    load_messages($('.ticket_msg'), ticket_id)
                    scrolled = 1
                }
            }
        })
    }
})


jQuery(document).ready(function () {

    $(".chat-list a").click(function () {
        $(".chatbox").addClass('showbox');
        return false;
    });

    $(".chat-icon").click(function () {
        $(".chatbox").removeClass('showbox');
    });


});




$(document).ready(function () {
    $(document).on('click', '#googleLogin', function (e) {
        e.preventDefault();
        googleSignIn();
    });
    $(document).on('click', '#facebookLogin', function (e) {
        e.preventDefault();
        facebookSignIn();
    });


    function googleSignIn() {
        var provider = new firebase.auth.GoogleAuthProvider();
        provider.addScope('email');
        firebase.auth().signInWithPopup(provider).then(function (result) {


            var type = 'google';
            var name = result.user.displayName;
            if (result.user.email != null && result.user.email != '') {
                var email = result.user.email
            } else if (result.user.providerData[0].email != null && result.user.providerData[0].email != '') {
                var email = result.user.providerData[0].email
            } else {
                var email = result.additionalUserInfo.profile.email
            }
            var password = result.user.uid;
            $.ajax({
                type: 'POST',
                url: base_url + 'home/verifyUser',
                data: {
                    email: email,
                    type: type,
                    [csrfName]: csrfHash
                },
                dataType: 'json',
                success: function (result) {
                    csrfName = result['csrfName'];
                    csrfHash = result['csrfHash'];

                    if (result.error == true) {
                        $.ajax({
                            type: 'POST',
                            url: base_url + 'auth/register_user',
                            data: {
                                type: type,
                                name: name,
                                email: email,
                                password: password,
                                [csrfName]: csrfHash
                            },
                            dataType: 'json',
                            success: function (result) {
                                csrfName = result['csrfName'];
                                csrfHash = result['csrfHash'];
                                if (result.error == false) {
                                    $.ajax({
                                        type: 'POST',
                                        url: base_url + 'home/login',
                                        data: {
                                            identity: email,
                                            type: type,
                                            password: password,
                                            [csrfName]: csrfHash
                                        },
                                        dataType: 'json',
                                        success: function (result) {
                                            cart_sync().then(function () {
                                                location.reload();
                                            });
                                        }
                                    });
                                }
                            }
                        });
                    } else {
                        $.ajax({
                            type: 'POST',
                            url: base_url + 'home/login',
                            data: {
                                identity: email,
                                type: type,
                                password: password,
                                [csrfName]: csrfHash
                            },
                            dataType: 'json',
                            success: function (result) {
                                cart_sync().then(function () {
                                    location.reload();
                                });
                            }
                        });
                    }
                }
            });

        }).catch(function (error) {

        });
    }

    function facebookSignIn() {
        var provider = new firebase.auth.FacebookAuthProvider();
        firebase.auth().signInWithPopup(provider).then(function (result) {
            var type = 'facebook';
            var name = result.user.displayName;
            var email = result.additionalUserInfo.profile.email;
            var password = result.user.uid;
            $.ajax({
                type: 'POST',
                url: base_url + 'home/verifyUser',
                data: {
                    email: email,
                    type: type,
                    [csrfName]: csrfHash
                },
                dataType: 'json',
                success: function (result) {
                    csrfName = result['csrfName'];
                    csrfHash = result['csrfHash'];
                    if (result.error == true) {
                        $.ajax({
                            type: 'POST',
                            url: base_url + 'auth/register_user',
                            data: {
                                type: type,
                                name: name,
                                email: email,
                                password: password,
                                [csrfName]: csrfHash
                            },
                            dataType: 'json',
                            success: function (result) {
                                csrfName = result['csrfName'];
                                csrfHash = result['csrfHash'];
                                if (result.error == false) {
                                    $.ajax({
                                        type: 'POST',
                                        url: base_url + 'home/login',
                                        data: {
                                            identity: email,
                                            type: type,
                                            password: password,
                                            [csrfName]: csrfHash
                                        },
                                        dataType: 'json',
                                        success: function (result) {
                                            cart_sync().then(function () {
                                                location.reload();
                                            });
                                        }
                                    });
                                }
                            }
                        });
                    } else {
                        $.ajax({
                            type: 'POST',
                            url: base_url + 'home/login',
                            data: {
                                identity: email,
                                type: type,
                                password: password,
                                [csrfName]: csrfHash
                            },
                            dataType: 'json',
                            success: function (result) {
                                cart_sync().then(function () {
                                    location.reload();
                                });
                            }
                        });
                    }
                }
            });
        }).catch(function (error) {
        });
    }
});

$(document).ready(function () {
    $("#share").jsSocials({
        showLabel: false,
        showCount: false,
        shares: ["twitter", "facebook", "whatsapp", "pinterest", "linkedin", "googleplus"]
    });
});


$(document).ready(function () {
    // Submit chat message to backend on form submit
    $(".reorder-btn").on("click", (event) => {
        const variants = ($(event.target).data("variants")) + ""
        const qty = ($(event.target).data("quantity")) + ""
        let html = $(event.target).html()
        $.ajax({
            type: "POST",
            url: base_url + "cart/manage",
            data: {
                product_variant_id: variants,
                qty: qty,
                is_saved_for_later: false,
                [csrfName]: csrfHash
            },
            dataType: "json",
            beforeSend: function () {
                $(event.target).text("Please Wait").attr("disabled", true)
            },
            success: function (res) {
                $(event.target).text(html).attr("disabled", false)
                window.location.href = base_url + "cart/checkout"
            }
        })

    })

});

function requestPermission() {
    Notification.requestPermission().then((permission) => {
        if (permission === 'granted') {
            console.log('Notification permission granted.');
        }
    })
}

$(document).ready(function () {
    // Show/hide chat iframe on chat button click
    $("#chat-button").on("click", function (e) {
        e.preventDefault();
        $("#chat-iframe").toggle();
        $(this).toggleClass("opened");
        $("#chat-iframe").toggleClass("opened");
    });
    $("#chat-with-button").on("click", function (e) {
        e.preventDefault();
        $("#chat-iframe").attr("src", base_url + "my-account/floating_chat_classic?user_id=" + $(this).data("id"));
        $("#chat-iframe").toggle();
        // $(this).toggleClass("opened");
        $("#chat-iframe").toggleClass("opened");
    });


});

var search_user = "";

$(document).ready(() => {
    var url = base_url + 'my-account/search_user';
    search_user = $('.search_user').select2({
        ajax: {
            url: base_url + 'my-account/search_user',
            type: "GET",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    search: params.term,
                };
            },
            processResults: function (response) {
                return {
                    results: response
                };
            },
            cache: true
        },
        dropdownParent: $("#floating_chat_view"),
        minimumInputLength: 1,
        theme: 'bootstrap4',
        placeholder: 'Search for countries',
    });
});



$(document).on('change', '#chat_user', function () {

    var oppo_user_id = JSON.parse($("#chat_user").val())
    var type = 'person';
    if ($(this).data("not_in_group") == true) {
        $("#chat_area_wait").addClass("d-none");
        $("#you_not_in_group").removeClass("d-none");
        $("#chat_area").addClass("d-none");
    } else {
        $("#chat_area_wait").addClass("d-none");
        $("#you_not_in_group").addClass("d-none");
        $("#chat_area").removeClass("d-none");
    }
    $(".floating-chat-users").addClass("d-none");

    $(".go-to-bottom-btn").hide();

    $('.chat-person').removeClass("active");
    $("#opposite_user_id").val(oppo_user_id);
    $("#chat_type").val(type);
    $(this).addClass("active");
    $("#chat-box-content").html('');
    switchChat(oppo_user_id, type);
    if (!!loaded_chat[type + '_' + oppo_user_id]) {

        var chat = loaded_chat[type + '_' + oppo_user_id]
        printChat(chat, oppo_user_id);

    } else {

        loadChat(oppo_user_id, type);
    }
    markMsgRead(oppo_user_id, type);

});

// function switchChat(from_id, type) {

//     $.ajax({
//         url: base_url + "my-account/switch_chat",
//         type: "POST",
//         data: {
//             from_id: from_id,
//             type: type
//         },
//         dataTpe: 'json',
//         success: function (result) {

//             var person = JSON.parse(result);

//             if (type == 'person') {
//                 $("#chat_title").text(person[0].username);

//                 var html = '<figure class="avatar avatar-md"><img src="' + base_url + 'assets/front_end/classic/images/user.png" class="rounded-circle avtar_img"></figure>';

//                 $("#chat-avtar-main").html(html);

//                 if (person[0].is_online == 1) {
//                     $("#chat_online_status").addClass("text-success");
//                     $("#chat_online_status").html("<i class='fa fa-circle'></i> Online <span class='text-info' id='chat_typing' style='display: none;'> Typing...</span>");
//                 } else {
//                     $("#chat_online_status").removeClass("text-success");
//                     $("#chat_online_status").html("<i class='fa fa-circle'></i> Offline");
//                 }

//             } else {


//                 $("#chat_title").html(person[0].title);
//                 var html = '<figure class="avatar avatar-md" data-initial="' + person[0].picture + '"></figure>';
//                 $("#chat-avtar-main").html(html);
//                 $("#chat_online_status").html('');
//             }

//         }
//     });

// }

// $(document).on('click', '.chat-person', function () {
//     if ($(this).data("not_in_group") == true) {
//         $("#chat_area_wait").addClass("d-none");
//         $("#you_not_in_group").removeClass("d-none");
//         $("#chat_area").addClass("d-none");
//     } else {
//         $("#chat_area_wait").addClass("d-none");
//         $("#you_not_in_group").addClass("d-none");
//         $("#chat_area").removeClass("d-none");
//     }
//     $(".floating-chat-users").addClass("d-none");
//     $(".go-to-bottom-btn").hide();
//     var oppo_user_id = $(this).data("id");
//     var type = $(this).data("type");
//     $('.chat-person').removeClass("active");
//     $("#opposite_user_id").val(oppo_user_id);
//     $("#chat_type").val(type);
//     $(this).addClass("active");
//     $("#chat-box-content").html('');
//     switchChat(oppo_user_id, type);
//     if (!!loaded_chat[type + '_' + oppo_user_id]) {

//         var chat = loaded_chat[type + '_' + oppo_user_id]
//         printChat(chat, oppo_user_id);

//     } else {

//         loadChat(oppo_user_id, type);
//     }
//     markMsgRead(oppo_user_id, type);

// });

// function markMsgRead(from_id, type) {
//     $.ajax({
//         url: base_url + "my-account/mark_msg_read",
//         type: "POST",
//         data: {
//             from_id: from_id,
//             type: type
//         },
//         dataTpe: 'json',
//         success: function (result) {

//             var person = JSON.parse(result);
//             if (person.error == false) {
//                 var i = $("li").find("[data-id='" + from_id + "']");
//                 i.find(".badge-chat").remove();
//                 i.removeClass('new-msg-rcv');
//                 i.data("unread_msg", 0);
//             } else {
//             }
//         }
//     });

// }

// $(document).on('keyup', '#chat-input-textarea', function () {
//     var char_length = $('#chat-input-textarea').val().length;
//     var text = $(this).val();
//     var convert = new Markdown.getSanitizingConverter().makeHtml;
//     var string = convert(text);
//     var chat_content = string.replace(/<[\/]{0,1}(p)[^><]*>/ig, "");
//     $('#chat-input-textarea-result').html(chat_content);
//     if (text != '') {
//         $('#chat-preview-btn').removeClass("d-none");
//         if (char_length % 9 == 0 || char_length == 1) {

//             var receiver_id = $("#opposite_user_id").val();
//             var title = 'typing';
//             var msg = 'typing';
//             var type = 'typing';
//             var msg_type = $("#chat_type").val();
//             sendFCM(receiver_id, title, msg, type, msg_type);

//         }
//     } else {
//         $('#chat-preview-btn').removeClass("d-none");
//     }
// });

// function sendFCM(receiver_id, title, msg, type, message_type = '') {
//     $.ajax({
//         url: base_url + "my-account/send_fcm",
//         type: "POST",
//         data: {
//             receiver_id: receiver_id,
//             title: title,
//             msg: msg,
//             type: type,
//             message_type: message_type
//         },
//         dataTpe: 'json',
//         success: function (result) {
//         }
//     });
// }


// function deleteMsg(msg_id) {
//     $.ajax({
//         url: base_url + "my-account/delete_msg/" + msg_id,
//         type: "POST",
//         data: csrfName + "=" + csrfHash,
//         success: function (result) {
//             var oppo_id = $("#opposite_user_id").val();
//             var type = $("#chat_type").val();
//             if (!!loaded_chat[type + '_' + oppo_id]) {

//                 for (var i = 0; i < loaded_chat[type + '_' + oppo_id].length; i++) {
//                     if (loaded_chat[type + '_' + oppo_id][i].id == msg_id) {
//                         loaded_chat[type + '_' + oppo_id].splice(i, 1);
//                     }
//                 }

//             }

//             $("[data-delete_msg_id='" + msg_id + "']").slideUp("normal", function () {
//                 $(this).remove();
//             });

//             var receiver_id = $("#opposite_user_id").val();
//             var title = 'msg deleted';
//             var msg = msg_id;
//             var type_1 = 'msg_delete';
//             sendFCM(receiver_id, title, msg, type_1, type);
//         }
//     });
// }

// $(document).on('keyup', 'textarea', function (event) {
//     if (event.keyCode == 13) {
//         var content = this.value;
//         var caret = getCaret(this);
//         if (event.shiftKey) {
//             this.value = content.substring(0, caret - 1) + "\n" + content.substring(caret, content.length);
//             var rowCount = $(this).attr("rows");
//             if (rowCount != 5) {
//                 $(this).attr({
//                     rows: parseInt(rowCount) + 1
//                 });
//             }
//             event.stopPropagation();
//         } else {
//             this.value = content.substring(0, caret - 1) + content.substring(caret, content.length);
//             $('#chat-form2').submit();
//         }
//     }
// });

// var loaded_chat = [];

// $(document).on("dragenter", "#chat-box-content", function (e) {
//     showDropZone();
// })

// window.closeDropZone = function () {
//     $('#chat-box-content').show();
//     $('#chat-dropbox').addClass("d-none");
//     Dropzone.forElement("#myAlbum").removeAllFiles(true);
// }

window.showDropZone = function () {
    $('#chat-dropbox').removeClass("d-none");
    $('#chat-box-content').hide();
}

function showDropZone() {
    window.showDropZone();
}

// Dropzone.autoDiscover = false;
// let chatDropZone;
// $(document).ready(function () {
//     // Dropzone initialization code here
//     chatDropZone = new Dropzone('#myAlbum', {
//         url: base_url + "my-account/send_msg",
//         autoProcessQueue: false,
//         paramName: "documents",
//         // dictDefaultMessage: dictDefaultMessage,
//         addRemoveLinks: true,
//         parallelUploads: 10,
//         uploadMultiple: true,
//         maxFiles: 3,
//         dictMaxFilesExceeded: 'Only 3 file are allow at once',
//         dictRemoveFile: 'x',
//         dictDefaultMessage: '<p><input type="submit" value="Select Files" class="btn btn-success" /><br> or <br> Drag & Drop Media Files Here</p>'
//     })

//     chatDropZone.on("addedfile", function (file) {
//         var i = 0;
//         if (this.files.length) {
//             var _i, _len;
//             for (_i = 0, _len = this.files.length; _i < _len - 1; _i++) // -1 to exclude current file
//             {
//                 if (this.files[_i].name === file.name && this.files[_i].size === file.size && this.files[_i].lastModifiedDate.toString() === file.lastModifiedDate.toString()) {
//                     this.removeFile(file);
//                 } else if (this.files[4] != null) {
//                     this.removeFile(file);

//                 }
//                 i++;
//             }
//         }
//     });

//     chatDropZone.on('successmultiple', function (file, response) {
//         var data = JSON.parse(response);
//         var new_msg = data.new_msg;
//         var to_id = $("#opposite_user_id").val();
//         var message = $("#chat-input-textarea").val();

//         var picture = '<figure class="avatar avatar-md"><img src="' + base_url + 'assets/front_end/classic/images/user.png" class="rounded-circle avtar_img"></figure>';


//         $.chatCtrl('#mychatbox2', {
//             text: new_msg[0].message,
//             picture: picture,
//             visiblity: '',
//             media_files: (!!new_msg[0].media_files) ? new_msg[0].media_files : '',
//             msg_id: (data.msg_id != undefined ? data.msg_id : ''),
//         }, 'bottom');

//         $('#chat-input-textarea-result').addClass("d-none");
//         $("#chat-input-textarea").val('');
//         $("#chat-box-content").find('.chat-text').addClass('selectable');

//         // make sure loaded_chat var declared before adding a msg in var when first time msg received from fcm this var is not declared
//         var type = $("#chat_type").val();
//         if (loaded_chat[type + '_' + to_id] != undefined) {
//             var chat_length = loaded_chat[type + '_' + to_id].length;
//             loaded_chat[type + '_' + to_id].unshift(Object.assign({}, new_msg[0]));
//         }
//         closeDropZone();
//         scrollToBottom();

//     });
// });


// function scrollToBottom() {
//     var target_height_send = 0;
//     var target_height_send_divider = 0;
//     $('.chat-content .chat-item').each(function () {
//         target_height_send += $(this).outerHeight();
//     });
//     $('.chat-content .chat_divider').each(function () {
//         target_height_send_divider += $(this).outerHeight();
//     });
//     target_height_send = target_height_send + target_height_send_divider + 1000;
//     $("#chat-box-content").scrollTop(target_height_send);
//     $(".go-to-bottom-btn").hide();
// }


// // sending msg
// $(document).on('submit', '#chat-form2', function (e) {
//     e.preventDefault();

//     var to_id = $("#opposite_user_id").val();
//     var type = $("#chat_type").val();
//     var my_user_id = $("#my_user_id").val();
//     var i = $("li").find("[data-id='" + my_user_id + "']");
//     var me = $(this);
//     var message = $("#chat-input-textarea").val();
//     var convert = new Markdown.getSanitizingConverter().makeHtml;
//     var string = convert(message);
//     var chat_content = string.replace(/<[\/]{0,1}(p)[^><]*>/ig, "");

//     var drop_file_count = chatDropZone.files.length;

//     if (message.length > 0) {
//         var formData = new FormData(this);

//         if (drop_file_count > 0) {

//             chatDropZone.on('sending', function (file, xhr, formData) {
//                 formData.append('opposite_user_id', jQuery('#opposite_user_id').val());
//                 formData.append('my_user_id', jQuery('#my_user_id').val());
//                 formData.append('chat_type', jQuery('#chat_type').val());
//                 formData.append('chat-input-textarea', jQuery('#chat-input-textarea').val());
//             });

//             chatDropZone.processQueue();

//             return false;

//         }


//         formData.append(csrfName, csrfHash);

//         $.ajax({
//             type: 'POST',
//             url: base_url + "my-account/send_msg",
//             data: formData,
//             cache: false,
//             contentType: false,
//             processData: false,
//             dataType: "json",
//             success: function (result) {

//                 var new_msg = result.new_msg;

//                 // make sure loaded_chat var declared before adding a msg in var when first time msg received from fcm this var is not declared
//                 if (loaded_chat[type + '_' + to_id] != undefined) {
//                     var chat_length = loaded_chat[type + '_' + to_id].length;
//                     loaded_chat[type + '_' + to_id].unshift(Object.assign({}, new_msg[0]));
//                 }
//                 var user_name = new_msg[0].senders_name;

//                 var picture = '<figure class="avatar avatar-md"><img src="' + base_url + 'assets/front_end/classic/images/user.png" class="rounded-circle avtar_img"></figure>';

//                 $.chatCtrl('#mychatbox2', {
//                     text: chat_content,
//                     picture: picture,
//                     user_name: user_name,
//                     visiblity: 1,
//                     media_files: '',
//                     msg_id: (result.msg_id != undefined ? result.msg_id : ''),
//                 }, 'bottom');

//                 scrollToBottom();
//                 var from_id = $("#opposite_user_id").val();
//                 var type = $("#chat_type").val();
//                 $.ajax({
//                     url: base_url + "my-account/load_chat",
//                     type: "POST",
//                     data: {
//                         from_id: from_id,
//                         type: type,
//                     },
//                     dataTpe: 'json',
//                     success: function (result) {
//                         var chats = JSON.parse(result);
//                         var html = ''
//                         var media_files = '';


//                         $.each(chats['msg'], function (key, val) {

//                             media_files = '';
//                             if (!!val.media_files) {

//                                 $.each(val.media_files, function (key, val) {
//                                     media_files += '<span class="chat-image-view d-grid">' +
//                                         '<a href="' + base_url + 'uploads/chat_media/' + val['original_file_name'] + '" download="' + val['original_file_name'] + '" class="download-btn-styling delete-msg fa fa-download"></a>' +
//                                         '<img width="150px" src="' + base_url + 'assets/backend/chats/' + val['file_name'] + '">' +
//                                         '</span>';
//                                 });
//                             }
//                             html += '<div class="text-title ml-2 mb-2 text-muted">' + val.group_name + ' - ' + moment(val.date_created).utc().format('MMM Do, YYYY') + '</div><li class="media"><div class="chat-avtar-search">' + val.picture + '</div><div class="media-body"><div class="float-right text-primary">' + moment(val.date_created).utc().format('hh:mm A') + '</div><div class="media-title">' + val.senders_name + '</div><span class="text-small text-muted">' + val.message + ' ' + media_files + '</span></div></li>'
//                         });


//                         $("#show-search-result").removeClass("d-none");
//                         $("#search-result").html(html);

//                     }
//                 });

//             }

//         });
//         $('#chat-input-textarea-result').addClass("d-none");
//         $("#chat-input-textarea").val('');
//         $("#chat-box-content").find('.chat-text').addClass('selectable');

//     } else {
//         if (drop_file_count > 0) {
//             chatDropZone.on('sending', function (file, xhr, formData) {
//                 formData.append('opposite_user_id', jQuery('#opposite_user_id').val());
//                 formData.append('my_user_id', jQuery('#my_user_id').val());
//                 formData.append('chat_type', jQuery('#chat_type').val());
//                 formData.append('chat-input-textarea', jQuery('#chat-input-textarea').val());
//             });

//             chatDropZone.processQueue();
//         }
//     }
//     return false;
// });

// $(document).on('keyup', '#in-chat-search', function () {

//     $("#search-result").html('');

//     var search = $("#in-chat-search").val();
//     var from_id = $("#opposite_user_id").val();
//     var type = $("#chat_type").val();
//     if (!!search) {
//         $.ajax({
//             url: base_url + "my-account/load_chat",
//             type: "POST",
//             data: {
//                 from_id: from_id,
//                 type: type,
//                 search: search
//             },
//             dataTpe: 'json',
//             success: function (result) {
//                 var chats = JSON.parse(result);
//                 var html = ''
//                 var media_files = '';


//                 $.each(chats['msg'], function (key, val) {

//                     media_files = '';
//                     if (!!val.media_files) {

//                         $.each(val.media_files, function (key, val) {
//                             media_files += '<span class="chat-image-view d-grid">' +
//                                 '<a href="' + base_url + 'uploads/chat_media/' + val['original_file_name'] + '" download="' + val['original_file_name'] + '" class="download-btn-styling delete-msg fa fa-download"></a>' +
//                                 '<img width="150px" src="' + base_url + 'assets/backend/chats/' + val['file_name'] + '">' +
//                                 '</span>';

//                         });
//                     }
//                     html += '<div class="text-title ml-2 mb-2 text-muted">' + val.group_name + ' - ' + moment(val.date_created).utc().format('MMM Do, YYYY') + '</div><li class="media"><div class="chat-avtar-search">' + val.picture + '</div><div class="media-body"><div class="float-right text-primary">' + moment(val.date_created).utc().format('hh:mm A') + '</div><div class="media-title">' + val.senders_name + '</div><span class="text-small text-muted">' + val.message + ' ' + media_files + '</span></div></li>'
//                 });


//                 $("#show-search-result").removeClass("d-none");
//                 $("#search-result").html(html);

//             }
//         });
//     } else {
//         $("#show-search-result").addClass("d-none");
//     }

// });

// $(document).on('click', '#modal-search-msg', function (e) {
//     $('#chat-search-modal').modal('show');
// });

// $(document).on('click', '#out-chat-search', function (e) {
//     $('.chat-person').removeClass("active");
//     $("#chat_type").val('');
//     $("#chat_area_wait").removeClass("d-none");
//     $("#chat_area").addClass("d-none");
//     $("#in-chat-search").val('');
//     $("#show-search-result").addClass("d-none");
// });

// function printChat(chats, id_of_user) {
//     if (0 < chats.length) {
//         var last_msg = chats.length - 1;
//         var picture = ''
//         var old_date = '';
//         for (var i = 0; i < chats.length; i++) {
//             var type = 'text';
//             var convert = new Markdown.getSanitizingConverter().makeHtml;
//             var string = convert(chats[i].text);
//             var chat_content = string.replace(/<[\/]{0,1}(p)[^><]*>/ig, "");
//             var is_divide = 'no';
//             var new_date = moment(chats[i].date_created).format('YYYYMMDD');

//             if (i == 0) {
//                 old_date = moment(chats[i].date_created).format('YYYYMMDD');
//                 is_divide = 'yes';
//             } else if (old_date != new_date) {
//                 is_divide = 'yes';
//                 old_date = new_date;
//             } else if (i == last_msg) {
//                 is_divide = 'yes';
//             }

//             picture = '<figure class="avatar avatar-md"><img src="' + base_url + 'assets/front_end/classic/images/user.png" class="rounded-circle avtar_img"></figure>';

//             if (chats[i].typing != undefined) type = 'typing';
//             $.chatCtrl('#mychatbox2', {
//                 text: (chats[i].text != undefined ? chat_content : ''),
//                 picture: picture,
//                 user_name: chats[i].senders_name,
//                 position: 'chat-' + chats[i].position,
//                 time: moment(chats[i].date_created).format('hh:mm A'),
//                 chat_divider: is_divide,
//                 chat_divider_date: chats[i].date_created,
//                 visiblity: '',
//                 media_files: (!!chats[i].media_files ? chats[i].media_files : ''),
//                 msg_id: (chats[i].id != undefined ? chats[i].id : ''),
//                 type: type
//             });

//             $("#chat-box-content").find('.chat-text').addClass('selectable');
//         }
//         $(".chat_loader").remove();
//         $("#chat-box-content").prepend('<div class="chat_loader">Loading...</div>');
//     } else {
//         $("#chat-box-content").html('');
//         $(".go-to-bottom-btn").hide();
//     }

//     var type = $("#chat_type").val();
//     if (!!loaded_chat[type + '_' + id_of_user]['msg_offset']) {

//         $("#chat-box-content").scrollTop(loaded_chat[type + '_' + id_of_user]['msg_offset']);
//     } else {
//         if (target_height === '') {
//             target_height = 640;
//         }
//         $("#mychatbox2").find('.chat-content').scrollTop(target_height, -1);
//     }

// }


// function loadChat(from_id, type, offset = '', limit = '', sort = '', order = '') {
//     offset = (!!offset) ? offset : 0;
//     limit = (!!limit) ? limit : 10;
//     $.ajax({
//         url: base_url + "my-account/load_chat",

//         type: "POST",
//         data: {
//             from_id: from_id,
//             type: type,
//             offset: offset,
//             limit: limit,
//             sort: sort,
//             order: order
//         },
//         dataTpe: 'json',
//         success: function (result) {
//             var chats = JSON.parse(result);
//             if (chats['error'] != true) {
//                 if (!!loaded_chat[type + '_' + from_id] && loaded_chat[type + '_' + from_id] != undefined) {
//                     loaded_chat[type + '_' + from_id] = loaded_chat[type + '_' + from_id].concat(chats['msg']);
//                     loaded_chat[type + '_' + from_id]['msg_loaded'] = chats['msg'].length;
//                     loaded_chat[type + '_' + from_id]['total_msg'] = chats['total_msg'];
//                     loaded_chat[type + '_' + from_id]['offset'] = offset;
//                     loaded_chat[type + '_' + from_id]['limit'] = limit;
//                 } else {
//                     loaded_chat[type + '_' + from_id] = chats['msg'];
//                     loaded_chat[type + '_' + from_id]['msg_loaded'] = chats['msg'].length;
//                     loaded_chat[type + '_' + from_id]['total_msg'] = chats['total_msg'];
//                     loaded_chat[type + '_' + from_id]['offset'] = offset;
//                     loaded_chat[type + '_' + from_id]['limit'] = limit;
//                 }
//                 printChat(chats['msg'], from_id);
//             }
//         }
//     });
// }
// function newLoadChat(from_id, type, offset = '', limit = '', sort = '', order = '') {
//     offset = (!!offset) ? offset : 0;
//     limit = (!!limit) ? limit : 10;
//     $.ajax({
//         url: base_url + "my-account/load_chat",
//         type: "POST",
//         data: {
//             from_id: from_id,
//             type: type,
//             offset: offset,
//             limit: limit,
//             sort: sort,
//             order: order
//         },
//         dataTpe: 'json',
//         success: function (result) {
//             var chats = JSON.parse(result);
//             if (chats['error'] != true) {
//                 if (!!loaded_chat[type + '_' + from_id] && loaded_chat[type + '_' + from_id] != undefined) {

//                     var new_msg_arved = 0;
//                     for (var i = 0; i < chats['msg'].length; i++) {
//                         if (loaded_chat[type + '_' + from_id][0].id < chats['msg'][i].id) {

//                             new_msg_arved++;
//                             new_msg_arrived = true;

//                             loaded_chat[type + '_' + from_id].unshift(Object.assign({}, chats['msg'][i]));
//                             loaded_chat[type + '_' + from_id]['msg_loaded'] = loaded_chat[type + '_' + from_id]['msg_loaded'] + new_msg_arved;
//                             loaded_chat[type + '_' + from_id]['total_msg'] = loaded_chat[type + '_' + from_id]['total_msg'] + new_msg_arved;

//                             var oppo_user_id = $("#opposite_user_id").val();
//                             var type1 = $("#chat_type").val();

//                             if (oppo_user_id == from_id && type1 == type) {
//                                 var convert = new Markdown.getSanitizingConverter().makeHtml;
//                                 var string = convert(chats['msg'][i].text);
//                                 var chat_content = string.replace(/<[\/]{0,1}(p)[^><]*>/ig, "");

//                                 var picture = '<figure class="avatar avatar-md"><img src="' + base_url + 'assets/front_end/classic/images/user.png" class="rounded-circle avtar_img"></figure>';

//                                 $.chatCtrl('#mychatbox2', {
//                                     text: chat_content,
//                                     picture: picture,
//                                     user_name: chats['msg'][i].senders_name,
//                                     position: 'chat-' + chats['msg'][i].position,
//                                     visiblity: 1,
//                                     media_files: (!!chats['msg'][i].media_files ? chats['msg'][i].media_files : ''),
//                                     msg_id: chats['msg'][i].id
//                                 }, 'bottom');

//                                 $("#chat-box-content").find('.chat-text').addClass('selectable');
//                             }

//                         }
//                     }

//                 }
//             }
//         }
//     });
// }

// Email verification and password reset functionality for classic theme
$(document).ready(() => {
    // Forgot password email functionality for classic theme
    $('#forgot-password-email-link').on('click', function (e) {
        e.preventDefault();
        $('#send_forgot_password_otp_form').hide();
        $('#forgot-password-email-form').removeClass('d-none').show();
        $('#forgot-password-phone-div').removeClass('d-none').show();
        $('#forgot-password-email-link').addClass('d-none');
    });

    $('#forgot-password-phone').on('click', function (e) {
        e.preventDefault();
        location.reload();
    });

    // Handle Firebase email reset
    $('#forgot-password-email-form').on('submit', function (e) {
        e.preventDefault();
        var email = $('#forgot_password_email').val();
        if (!email) {
            $('#forgot_pass_email_error_box').html('<span class="text-danger">Please enter your email.</span>');
            return;
        }
        $('#send_firebase_reset_email_btn').attr('disabled', true).text('Sending...');
        firebase.auth().sendPasswordResetEmail(email)
            .then(function () {
                $('#forgot_pass_email_error_box').html('<span class="text-success">Password reset email sent! Please check your inbox.</span>');
                $('#send_firebase_reset_email_btn').attr('disabled', false).text('Send Reset Email');
            })
            .catch(function (error) {
                $('#forgot_pass_email_error_box').html('<span class="text-danger">' + error.message + '</span>');
                $('#send_firebase_reset_email_btn').attr('disabled', false).text('Send Reset Email');
            });
    });

    let paramQueries = new URLSearchParams(window.location.search);
    if (window.location.pathname.includes("register")) {
        let mode = paramQueries.get("mode");
        let oobCode = paramQueries.get("oobCode");

        let registerForm = document.getElementById("register_div");
        let loginText = document.getElementById("login-text");
        let resetForm = document.getElementById("resetForm");

        if (mode === "verifyEmail" && oobCode) {
            // Handle email verification
            if (registerForm) registerForm.style.display = "none";
            if (loginText) loginText.style.display = "none";
            if (resetForm) resetForm.style.display = "none";

            // Apply the email verification code
            firebase.auth().applyActionCode(oobCode)
                .then(() => {
                    
                    Toast.fire({
                        title: 'Email Verified!',
                        icon: 'success',
                    }).then(() => {
                        location.href = base_url;
                    });
                })
                .catch((error) => {
                    
                    let errorMessage = "Invalid or expired verification link";

                    // Handle specific error codes
                    switch (error.code) {
                        case 'auth/expired-action-code':
                            errorMessage = "This verification link has expired. Please request a new one.";
                            break;
                        case 'auth/invalid-action-code':
                            errorMessage = "This verification link is invalid or has already been used.";
                            break;
                        case 'auth/user-disabled':
                            errorMessage = "This user account has been disabled.";
                            break;
                        case 'auth/user-not-found':
                            errorMessage = "No user found for this verification link.";
                            break;
                    }

                    Swal.fire({
                        title: 'Verification Failed',
                        text: errorMessage,
                        icon: 'error',
                        confirmButtonText: 'Go to Homepage',
                        allowOutsideClick: false,
                        allowEscapeKey: false
                    }).then(() => {
                        location.href = base_url;
                    });
                });
        } else if (mode === "resetPassword" && oobCode) {
            // Hide registration form
            if (registerForm) registerForm.style.display = "none";
            if (loginText) loginText.style.display = "none";
            if (resetForm) resetForm.style.display = "block";

            // Verify reset code
            firebase.auth().verifyPasswordResetCode(oobCode)
                .then((email) => {
                    
                    Toast.fire({
                        icon: "success",
                        title: "Enter your new Password"
                    });
                    window.resetEmail = email;
                })
                .catch((error) => {
                    
                    Toast.fire({
                        icon: "error",
                        title: "Invalid or expired link"
                    });
                    resetForm.style.display = "none";
                    delete window.resetEmail;
                    location.href = base_url;
                });

            // Handle reset form submit
            resetForm.addEventListener("submit", function (e) {
                e.preventDefault();
                const newPassword = document.getElementById("newPassword").value;
                const email = window.resetEmail;

                firebase.auth().confirmPasswordReset(oobCode, newPassword)
                    .then(() => {
                       
                        // Update password in Database
                        $.ajax({
                            url: 'home/reset-password',
                            type: 'POST',
                            data: {
                                email: email,
                                new_password: newPassword
                            },
                            beforeSend: function () {
                                console.log("Sending request to reset MySQL password..." + email + " " + newPassword);
                            },
                            success: function (response) {
                                const res = JSON.parse(response);
                                if (res.error) {
                                    
                                    Toast.fire({
                                        icon: "error",
                                        title: res.message
                                    });
                                } else {
                                    
                                    Toast.fire({
                                        icon: "success",
                                        title: "Password has been reset successfully in both systems!"
                                    });
                                    resetForm.style.display = "none";
                                    location.href = base_url;
                                }
                            },
                            error: function (xhr, status, error) {
                                
                                Toast.fire({
                                    icon: "error",
                                    title: "Failed to update password in database"
                                });
                                delete window.resetEmail;
                            }
                        });
                    })
                    .catch((error) => {
                        
                        Toast.fire({
                            icon: "error",
                            title: "Invalid or expired link"
                        });
                        delete window.resetEmail;
                        location.href = base_url;
                    });
            });
        } else {
            if (registerForm) registerForm.style.display = "block";
            if (resetForm) resetForm.style.display = "none";
        }
    }

    // Initialize email/phone form flags
    let isEmailLoginMode = false;

    // Toggle between email and phone login
    $('#login-emailLogin').on('click', function (e) {
        e.preventDefault();
        $('#mobile-form').addClass('d-none');
        $('#email-form').removeClass('d-none');
        $('.login-email-login').addClass('d-none');
        $('.login-phone-login').removeClass('d-none');
        isEmailLoginMode = true;
    });

    $('#login-phoneLogin').on('click', function (e) {
        e.preventDefault();
        $('#email-form').addClass('d-none');
        $('#mobile-form').removeClass('d-none');
        $('.login-phone-login').addClass('d-none');
        $('.login-email-login').removeClass('d-none');
        isEmailLoginMode = false;
    });
});
$(document).on('click', '.copy-button', function (e) {
    /* Get the text to copy */
    const text = document.getElementById("text-to-copy").innerText;

    /* Create a temporary input element */
    const tempInput = document.createElement("input");
    tempInput.type = "text";
    tempInput.value = text;
    document.body.appendChild(tempInput);

    /* Select and copy the text */
    tempInput.select();
    document.execCommand("copy");

    /* Remove the temporary input element */
    document.body.removeChild(tempInput);

    /* Update the copy button text */
    const copyButton = document.querySelector(".copy-button");
    copyButton.innerText = "Copied!";
    setTimeout(function () {
        copyButton.innerText = "Tap to copy";
    }, 1000);
});
function transactionQueryParams(params) {
    return {
        offset: params.offset,
        limit: params.limit,
        search: params.search,
        sort: params.sort,
        order: params.order,
        status: $('#status_filter').val()
    };
}

/* Refresh table on filter change */
$('#status_filter').on('change', function () {
    $('#transaction_table').bootstrapTable('refresh');
});