function baseurl() {
    var t = window.location;
    return "localhost" == t.host ? t.protocol + "//" + t.host + "/delespesialisten/" : t.protocol + "//" + t.host + "/";
}
function delivery_link(t) {
    var t = t;
    $(".delivery_form_" + t).toggle();
}
function get_delivery_date(t, a, r) {
    if ("del_date" == a) var i = $(".delivery_date_" + t).val();
    $.ajax({
        type: "POST",
        data: { pro_id: t, type: a, ship_from: 3221, ship_to: i, articlenr: r },
        url: baseurl() + "ajax/deliverydate",
        dataType: "json",
        success: function (t) {
            return (
                $.each(t, function (t, a) {
                    var r = a.output;
                    a.selector,
                        "must be a valid postal code in NORWAY" != r && "topostalcode is required" != r
                            ? ($(".delivery_app_err" + a.class_selector).html(""), $(".delivery_app_" + a.class_selector).html(r))
                            : ($(".delivery_app_" + a.class_selector).html(""),
                                "must be a valid postal code in NORWAY" == r
                                    ? $(".delivery_app_err" + a.class_selector).html("Must be a valid postal code in NORWAY")
                                    : $(".delivery_app_err" + a.class_selector).html("Postal code is required"));
                }),
                !1
            );
        },
    });
}
function getsum(t, a) {
    if ("add" == t) {
        var r = $(a).prev(".myquans").val();
        return ++r > 0 && $(a).prev(".myquans").val(r), !1;
    }
    if ("sub" != t) return !1;
    var i = $(a).next(".myquans").val();
    return --i > 0 && $(a).next(".myquans").val(i), !1;
}
function validation(t, a, r, i = []) {
    var o = {};
    (o.rules = a),
        (o.messages = r),
        (o.errorElement = i.errorElement ? i.errorElement : "p"),
        (o.errorClass = i.errorClass ? i.errorClass : "error_class_1"),
        (o.ignore = i.ignore ? i.ignore : ":hidden"),
        (o.errorPlacement = function (t, a) {
            t.insertAfter(a);
        });
    var l = $(t).validate(o);
    if (i.callback) return l;
}
function loginmodal() {
    $.ajax({
        type: "GET",
        data: {},
        url: baseurl() + "user/login",
        success: function (t) {
            $(".usermodal").html(""), $(".usermodal").html(t), $("#loginmodal").modal("show");
        },
    });
}

function userlogin(redirectUrl) {
    // Gather input values
    $('#log_submit').attr('disabled', true);
    var email = $("#email").val(),
        passcode = $("#passcode").val(),
        rememberMe = $("#remember_me").is(':checked'), // Changed to use is(':checked') for boolean value
        currentUrl = window.location.href,
        urlSegments = currentUrl.split("/"),
        lastSegment = urlSegments[urlSegments.length - 1];

    // Default redirect URL if not provided
    var defaultRedirectUrl = 'utilizator/mine-ordre';

    // Validate input fields
    if (email === "" || passcode === "") {
        $("#loginform_err").html("Please enter both email and passcode.");
        $('#log_submit').attr('disabled', false);
        return false;
    }

    // Perform AJAX request
    $.ajax({
        type: "POST",
        data: { email_id: email, passcode: passcode, remember_me: rememberMe },
        url: baseurl() + "userlogin",
        dataType: "json",
        success: function (response) {
            console.log(response);

            // Handle different response cases
            if (response === 0) {
                $("#loginform_err").html("Feil e-post/passord!");
                $('#log_submit').attr('disabled', false);
                return false;
            }

            if (response === 2) {
                $("#loginform_err").html("E-postadressen din er ikke aktivert. Du har mottatt en aktiveringskobling for e-post");
                $('#log_submit').attr('disabled', false);
                return false;
            }
            if (response == 4) {
                $("#loginform_err").html("");
                authenticationmodal();
            }
            if (response == 1) {

                $("#loginform_err").html("");
                $("#msg").html('<div class="alert alert-success alert-dismissible">Bruker logget på vellykket</div>');

                var redirectTo = (currentUrl !== "1" && (lastSegment === "checkout" || lastSegment === "cart")) ? currentUrl : (redirectUrl || defaultRedirectUrl);
                window.setTimeout(function () {
                    window.location.href = baseurl() + redirectTo;
                }, 2000);
            }

        },
        error: function (xhr, status, error) {
            // Handle any AJAX errors
            console.error("AJAX Error: ", status, error);
            $("#loginform_err").html("En feil oppstod. Vennligst prøv igjen.");
            $('#log_submit').attr('disabled', false);
        }
    });
}

function authenticationmodal() {
    $.ajax({
        type: "GET",
        data: {},
        url: baseurl() + "user/authentication",
        success: function (t) {
            $(".user__modal").html(""), $(".user__modal").html(t), $("#verificationmodal").modal("show");
            $('#verificationmodal .close').click(function () {
                $('#log_submit').attr('disabled', false);
            });
        },
        error: function (xhr, status, error) {
            $('#log_submit').attr('disabled', false);
            console.error("AJAX Error: ", status, error);
        }
    });
}

function logout() {
    for (var t = document.cookie.split(";"), a = 0; a < t.length; a++) {
        var r = t[a],
            i = r.indexOf("="),
            o = i > -1 ? r.substr(0, i) : r;
        document.cookie = o + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}
function forgotpassword() {
    var t = $("#emailid").val();
    if ("" == t.trim()) return !1;
    $.ajax({
        type: "POST",
        data: { email_id: t },
        url: baseurl() + "forgotpassword",
        dataType: "json",
        success: function (t) {
            console.log(t);
            if (!(t > 0))
                return (
                    $("#msg").html('<div class="alert alert-danger alert-dismissible">Problem med e-postfunksjon. Vennligst prøv senere.<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>'), !1
                );
            $("#loginform_err").html(""),
                $("#msg").html(
                    '<div class="alert alert-success alert-dismissible">En e-post med instrukser for tilbakestilling av passord har blitt sendt til din registrerte e-postadresse. Husk \xe5 sjekke s\xf8ppelpost dersom e-posten ikke dukker opp i innboksen.<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>'
                );
        },
    });
}
function ajaxdatatables(t, a = {}, r = null) {
    a.destroy && 1 == a.destroy && $(t).DataTable().destroy();
    var i = {
        destroy: !0,
        responsive: !0,
        autoWidth: !1,
        oLanguage: {
            sProcessing: "<div class='full_spinner'><img src='" + baseurl() + "assets/frontend/images/img/Spinner.gif' class='spinner2'></div>",
            sSearch: "S\xf8k",
            sInfo: "Viser _START_ til _END_ av _TOTAL_ oppf\xf8ringer",
            sLengthMenu: "Vis _MENU_ oppf\xf8ringer",
            sEmptyTable: "Ingen data tilgjengelig",
            sInfoEmpty: "Viser 0 til 0 av 0 oppf\xf8ringer",
            oPaginate: { sNext: "Frem", sPrevious: "Tilbake" },
        },
        processing: !0,
        serverSide: !0,
        ajax: {
            url: a.url,
            data: a.data ? a.data : {},
            dataType: "json",
            type: a.method ? a.method : "post",
            complete: function (t, a) {
                tooltip();
                var i = t.responseJSON;
                if ("mine-ordre" == r && "success" == a) {
                    var o = i.data;
                    $("#totalprice").html(i.totalprice), o.length > 0 && redraw_orders();
                }
                ("warranty_issue" == r || "return_orders" == r) && "success" == a && redraw_dataTable(i.data);
            },
        },
        columns: a.columns,
        initComplete: function () {
            $('#pointdatatable input')
                .unbind()
                .bind('input', function (e) {
                    if (this.value.length > 3) {
                        console.log('if');
                        table.search(this.value).draw();
                    } else {
                        console.log('else');
                        // Optionally clear the search if length is not greater than 3
                        return;
                    }
                });
        },
        createdRow: function (t, a, r) {
            $(t).addClass("row-" + r);
        },
        order: a.order ? a.order : [[0, "asc"]],
        columnDefs: a.columndefs ? a.columndefs : [],
        searching: !a.search || "0" != a.search,
        lengthMenu: a.lengthmenu && a.lengthmenu.length > 0 ? a.lengthmenu : [25, 50, 100],
        drawCallback: function () {
            let scrollPosition = window.scrollY;
            if(scrollPosition<=200){ scrollPosition = 470; }
            window.scrollTo(0, scrollPosition);
        },
    },
        o = $(t).DataTable(i);
    $(document).on("resize", function () {
        o.columns.adjust().responsive.recalc();
    });


}
function tooltip() {
    $('[data-toggle="tooltip"]').tooltip();
}
function qty(t, a) {
    console.log(a);
    var r = "#quantity" + a + "_err",
        i = (t = t || window.event).which ? t.which : t.keyCode;
    return i > 31 && (i < 48 || i > 57) ? ($(r).html("Kun tall tillatt"), !1) : ($(r).html(""), !0);
}
function getCookieValue(t) {
    for (var a = t + "=", r = decodeURIComponent(document.cookie).split(";"), i = 0; i < r.length; i++) {
        for (var o = r[i]; " " === o.charAt(0);) o = o.substring(1);
        if (0 === o.indexOf(a)) return o.substring(a.length, o.length);
    }
    return "";
}
jQuery(document).ready(function () {
    jQuery(".mob-bur i").click(function () {
        jQuery(".menu-section ul.menu-list li").toggle("show");
    });
}),
    $(document).ready(function () {
        $(".shw__po").hover(function () {
            $(".pop__div").toggleClass("show");
        });
        $(".log__con").hover(function () {
            $(".user__panel").toggleClass("show");
        });


        // To toggle side bar start

         $('.base_menu li div').click(function () {
            var $menuList = $(this).siblings('.menu--list');
            if ($menuList.css('max-height') == '0px') {
                var scrollHeight = $menuList.prop('scrollHeight') + 'px';
                $menuList.css('max-height', scrollHeight);
                setTimeout(function () {
                    $menuList.css('max-height', 'fit-content');
                }, 500);
            } else {
                $menuList.css('max-height', $menuList.prop('scrollHeight') + 'px');
                $menuList[0]?.offsetHeight;
                $menuList.css('max-height', '0');
            }
            if ($menuList.length) {
                $(this).find('.angle_up').toggleClass('d_none');
                $(this).find('.angle_down').toggleClass('d_none');
            }
        });
        var currentPage = $('#currentPage').val();
        
        setTimeout(()=>{
            let child = $('li.active');
            if (child.length) {
                console.log('inside');
                let l = child.parent('ul').closest('li');
                l.find('div').first().click();
                let parentLi = l.closest('ul').closest('li');
                if (parentLi.length) {
                    parentLi.find('div').first().click();
                }
                
                let layerThree = parentLi.closest('ul').closest('li');
                if (layerThree.length) {
                    layerThree.find('div').first().click();
                }

                let layerFour = layerThree.closest('ul').closest('li');
                if (layerFour.length) {
                    layerFour.find('div').first().click();
                }
                
            }else{
                if (currentPage == 'bildeler') {
                    $('.bildeler').click();
                }
                if (currentPage == 'universal') {
                    $('.universal').click();
                }
            }
        }, 1000);
        // To toggle side bar start


    }),
    $("document").ready(function () {
        $("button.next").click(function () {
            $(".slider").animate({ marginLeft: "-=33.1%" }, 300, function () {
                $(".slide:first").appendTo($(this)), $(this).css("margin-left", 0);
            });
        }),
            $("button.prev").click(function () {
                $(".slide:last").prependTo($(".slider")), $(".slider").css("margin-left", "-33.1%").animate({ marginLeft: "+=33.1%" }, 300);
            }),
            $(".cls-bt").click(function () {
                $(".homepgpop").fadeOut(300), location.reload(!0);
            }),
            $(".homepgpop").on("blur", function () {
                $(this).fadeOut(300);
            });
    }),
    $(document).ready(function () {
        $(".delivery_link").click(function () {
            var t = $(this).attr("data-id");
            $(".delivery_form_" + t).toggle();
        });
    }),
    $(document).on("click", ".mycartbutton, .addcartitem", function () {
        var t = $(this).attr("data-id"),
            a = $("#totalcat").val(),
            dd = $(this).prev().val(),
            ddd = $(this).prev().find('input').val();
        if (
            ((d = dd ? dd : ddd),
                (e = $(this).attr("data-tcd")),
                (f = $(this).attr("data-weight")),
                (li = $(this).attr("data-license")),
                (price_nto = $("#price_nto_exvat" + t).val()),
                (s = $("#supplier_id" + t).val()),
                (link = $(this).attr("data-url")),
                (title = $(this).attr("data-title")),
                (warehouse_delivery = $(this).attr("data-supplier")),
                (eddate = $("#eddate" + t).val()),
                "-1" == t)
        )
            return $(".popup").addClass("active"), !1;
        $.ajax({
            type: "POST",
            data: { product_id: t, quantity: d, ajax: "1", tcd: e, licenseplate_id: li, weight: f, supplier_id: s, warehouse_delivery: warehouse_delivery, price_nto: price_nto, link: link, title: title, eddate: eddate, totalcat: a },
            url: baseurl() + "ajax/add_cart_item",
            success: function (a) {
                return product_addcart(t, d, e), $("#pdt_append").html(""), $("#pdt_append").html(a), $(".homepgpop, .hom-popup-sec").fadeIn(300), !1;
            },
        });
    }),
    $(document).on("click", ".showcart", function () {
        $(".homepgpop, .hom-popup-sec").fadeIn(300);
    }),
    $(document).ready(function () {
        $("#loginmodal").on("hidden.bs.modal", function () {
            location.reload();
        });
    }),
    $(document).ready(function () {
        var t = null;
        $("#search-box").keyup(function () {
            var a = $("#type_id").val(),
                r = $(this).val();
            null != t && t.abort(),
                "" != r && r.length > 3
                    ? (t = jQuery.ajax({
                        type: "POST",
                        url: baseurl() + "/search/productsearch",
                        data: { type_id: a, keyword: $(this).val() },
                        beforeSend: function () {
                            $(".spinner").show();
                        },
                        success: function (t) {
                            $(".spinner").hide(), $(".searchdiv").show(), $("#suggesstion-box").attr("style", "display:block"), $("#suggesstion-box").html(t);
                        },
                        error: function (t) { },
                    }))
                    : ($(".spinner").hide(), $(".searchdiv").hide(), $("#searchdiv .fot-list li").empty(), $("#suggesstion-box div").html(""), $("#suggesstion-box").attr("style", "display:none"));
        });
    }),
    jQuery(document).ready(function () {
        $('.categories--show').click(function() {
            var $categoryList = $('.mobile-category-list');
            var $button = $(this);
            var $angleUp = $button.find('.angle_up');
            var $angleDown = $button.find('.angle_down');
                $categoryList.slideToggle(500, function() {
                if ($categoryList.is(':visible')) {
                    $angleUp.removeClass('d_none');
                    $angleDown.addClass('d_none');
                } else {
                    $angleUp.addClass('d_none');
                    $angleDown.removeClass('d_none');
                }
            });
            $button.toggleClass('show-angle-up');
        });
    });
    $(".menu__checkbox").click(function () {
        console.log("Menu");
        "none" == $(".mobilemenu__sec .sd__bar").css("display") ? $("html").addClass("sdactive") : $("html").removeClass("sdactive"), $(".mobilemenu__sec .sd__bar ").slideToggle();
    }),
    $(".logged__in").click(function () {
        $(".logged__toggle.login--header").slideToggle();
    });
    //2FA module
    function sendVerification(channel) {
        if (channel != '') {
            $.ajax({
                type: "POST",
                data: { 'channel': channel },
                url: baseurl() + "twilio/send-verification",
                success: function (t) {
                    $('#channel-err').html('');
                    if (channel == 'sms') {
                        $('.otp-phone').show();
                    } else if (channel == 'call') {
                        $('.otp-phone').show();
                    } else {
                        $('.otp-email').show();
                    }
                    $('.auth-otp').show();
                    $('.sendbtn').hide();
                    $('.verifybtn').show();
                    $('.custom--btn').prop('disabled', false);
                },
                error: function (xhr, status, error) {
                    $('#channel-err').html('Kunne ikke sende bekreftelseskoden. Vennligst prøv igjen.');
                    return false;
                }
            });
        }
    }

    function verifyCode() {
        const selectedChannel = document.querySelector('input[name="channel"]:checked');
        if (!selectedChannel) {
            $('#channel-err').html('Verifikasjonsmetode er nødvendig!');
            return false;
        }
        const inputs = document.querySelectorAll('input[name="otp[]"]');
        const inputArray = Array.from(inputs);
        const allFilled = inputArray.every(input => input.value.length === 1);

        if (!allFilled) {
            $('#otp-err').html('OTP kreves!');
            return false;
        }
        if (!selectedChannel || !allFilled) {
            return false;
        } else {
            $('#channel-err').html(''); $('#otp-err').html('');
            var formData = $('#authform').serialize();
            $.ajax({
                type: "POST",
                data: $('#authform').serialize(),
                url: baseurl() + "twilio/verify-code",
                success: function (t) {
                    console.log(t);
                    if (t.trim() == 'approved') {
                        $('#auth_msg').html('<div class="alert alert-success alert-dismissible fade show" role="alert"><i class="fa fa-check-circle" style="color: green; margin-right: 10px;"></i>Du har verifisert kontoen din!</div>');
                        window.setTimeout(function () {
                            $("#verificationmodal").modal("hide");
                            window.location.href = baseurl() + 'utilizator/mine-ordre';
                        }, 3000);

                    } else {
                        $('#auth_msg').html('<div class="alert alert-danger"><i class="fa-solid fa-circle-xmark" style="color: #de1a1a; margin-right: 10px;"></i>Bekreftelsen mislyktes. Prøv igjen!</div>');
                    }
                },
            });
        }
    }

    function triggerOTP() {
        const selectedChannel = document.querySelector('input[name="channel"]:checked');
        if (!selectedChannel) {
            $('#channel-err').html('Verifikasjonsmetode er nødvendig!');
            return false;
        } else {
            $('#channel-err').html('');
            const channel = selectedChannel.value;
            console.log(channel);

            // Select all input elements with the class 'form-control'
            const otpInputs = document.querySelectorAll('#otp .form-control');

            // Iterate over each input element and set its value to an empty string
            otpInputs.forEach(input => {
                input.value = '';
            });

            sendVerification(channel);
        }
    }

    function triggerChannel()
    {
        $('.otp-phone').hide();
        $('.otp-email').hide();
        $('.auth-otp').hide();
        $('.verifybtn').hide();
        $('.sendbtn').show();
    }
//2FA module
//CarInfo display with show-more, show-less function 29/10/2024
document.querySelectorAll('.left--section').forEach(section => {
    const buttons = section.querySelectorAll('.more--less button');
    const details = section.querySelector('.details');
    const detailsFull = section.querySelector('.details-full');

    buttons.forEach(button => {
        button.addEventListener('click', function() {
            if (detailsFull.style.display === 'none' || !detailsFull.style.display) {
                details.style.display = 'none';
                detailsFull.style.display = 'block';
                buttons.forEach(btn => {
                    btn.innerHTML = `<p>Se mindre <span><i class="fa-solid fa-chevron-up"></i></span></p>`;
                });
            } else {
                details.style.display = 'flex';
                detailsFull.style.display = 'none';
                buttons.forEach(btn => {
                    btn.innerHTML = `<p>Se mer <span><i class="fa-solid fa-chevron-down"></i></span></p>`;
                });
            }
        });
    });
});
//CarInfo display with show-more, show-less function 29/10/2024