<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>
<script src="<?= base_url(); ?>assets/starrr/dist/starrr.js"></script>
<script src="<?= base_url(); ?>assets/select2-4.0.6-rc.1/dist/js/select2.min.js"></script>
<script>
    const years = new Date().getFullYear();
    $("#footer-cr-years").text(years);

    const modalDelayPopup = "<?= $banner_popup['delay'] ?>";
    if (modalDelayPopup) {
        setTimeout(() => {
            $("#modalBannerPopup").modal("show");
        }, modalDelayPopup * 1000);
    }

    $('.starrr').starrr()
    $(".starrr").on('starrr:change', function(e, value) {
        $("input.starrr-rating-star-count").val(value);
    })

    $(".rating .top-rating").on("click", function() {
        $(".rating .main-rating").slideToggle();
        $(".rating .top-rating i").toggleClass("arrow-bottom-rating-rotate");
        $(".rating .top-rating i").css("transition", "0.5s");
    })

    $(".btn_order_now_checkout_page").on("click", function() {
        const pay = $("#paymentSelectCheckoutPage").val();
        $('#msgPaymentFirstCheckoutPage').hide();
        if (pay == "") {
            $('#msgPaymentFirstCheckoutPage').show();
        }
    })

    $("#btnFormHelpPojokKananBawah").on("click", function() {
        const name = $("#formHelpInputNamePojokKananBawah").val();
        const message = $("#formHelpTextareaMessagePojokKananBawah").val();
        const wa = "<?= $this->Settings_model->getSetting()['wa_admin']; ?>";
        const msgOpen = "<?= $this->Settings_model->getSetting()['message_chat_help']; ?>";
        if (name != "" && message != "") {
            $("#formHelpInputNamePojokKananBawah").val("");
            $("#formHelpTextareaMessagePojokKananBawah").val("");
            window.open(`https://wa.me/${wa}?text=${msgOpen}, saya ${name} ingin bertanya %0A ${message}`);
        }
    })

    $("button.btn-chat-help-pojok-kanan-bawah").on('click', function() {
        $("div.box-chat-help-wa").slideToggle('fast');
        // $("button.btn-chat-help-pojok-kanan-bawah i").removeClass("fa-whatsapp")
        // $("button.btn-chat-help-pojok-kanan-bawah i").removeClass("fab")
        // $("button.btn-chat-help-pojok-kanan-bawah i").addClass("fa")
        // $("button.btn-chat-help-pojok-kanan-bawah i").addClass("fa-times")
        // $("button.btn-chat-help-pojok-kanan-bawah i").css("font-size", "35px")
    })

    let numberOfSocialProof = 1;
    let numberOfInvoiceTotal = parseInt($("#numberOfInvoiceTotalHomePage").val()) * 1000;
    let pauseOfSocialProof = parseInt('<?= $this->Settings_model->general()['pause_social_proof']; ?>') * 1000;
    let timeOfSocialProof = parseInt('<?= $this->Settings_model->general()['time_social_proof']; ?>') * 1000;

    function showHideSocialProof() {
        $(`#socialProofId-${numberOfSocialProof}`).css("bottom", "20px");
        setTimeout(function() {
            $(`#socialProofId-${numberOfSocialProof}`).css("bottom", "-100px");
            numberOfSocialProof++;
        }, pauseOfSocialProof);
        if (numberOfSocialProof <= numberOfInvoiceTotal) {
            setTimeout(showHideSocialProof, pauseOfSocialProof * 2);
        } else {
            $(`div.social-proof`).css("bottom", "-100px");
            numberOfSocialProof = 0;
            setTimeout(showHideSocialProof, pauseOfSocialProof * 2);
        }
    }
    setTimeout(showHideSocialProof, timeOfSocialProof);

    // detail slick img
    $('.img-detail-product-slick').slick();
    $("div.wrapper div.top div.main-top div.img button.slick-prev").html(`<i class="fa fa-angle-left"></i>`);
    $("div.wrapper div.top div.main-top div.img button.slick-next").html(`<i class="fa fa-angle-right"></i>`);

    // load more product
    let startLoadProductHome = 8;
    $("#btnClickLoadMoreProductHome").on("click", function() {
        $("img.loading-animation-load-more").show();
        $(this).hide();
        $.ajax({
            url: "<?= base_url(); ?>products/get_more_product_home?start=" + startLoadProductHome,
            method: "get",
            success: function(response) {
                startLoadProductHome += 8;
                if (response == "") {
                    $("#btnClickLoadMoreProductHome").hide();
                    $("img.loading-animation-load-more").hide();
                } else {
                    $("#bodyForShowProductHome").append(response);
                    $("img.loading-animation-load-more").hide();
                    $("#btnClickLoadMoreProductHome").show();
                }
            }
        })
    })

    let startLoadProduct = 8;
    $("#btnClickLoadMoreProduct").on("click", function() {
        $("img.loading-animation-load-more").show();
        $(this).hide();
        $.ajax({
            url: "<?= base_url(); ?>products/get_more_product?start=" + startLoadProduct,
            method: "get",
            success: function(response) {
                startLoadProduct += 12;
                if (response == "") {
                    $("#btnClickLoadMoreProduct").hide();
                    $("img.loading-animation-load-more").hide();
                } else {
                    $("#bodyForShowProduct").append(response);
                    $("img.loading-animation-load-more").hide();
                    $("#btnClickLoadMoreProduct").show();
                }
            }
        })
    })

    let startLoadBestProduct = 12;
    $("#btnClickLoadMoreBestProduct").on("click", function() {
        $("img.loading-animation-load-more").show();
        $(this).hide();
        $.ajax({
            url: "<?= base_url(); ?>products/get_more_best_product?start=" + startLoadBestProduct,
            method: "get",
            success: function(response) {
                startLoadBestProduct += 12;
                if (response == "") {
                    $("#btnClickLoadMoreBestProduct").hide();
                    $("img.loading-animation-load-more").hide();
                } else {
                    $("#bodyForShowProduct").append(response);
                    $("img.loading-animation-load-more").hide();
                    $("#btnClickLoadMoreBestProduct").show();
                }
            }
        })
    })

    let startLoadProductCategory = 12;
    $("#btnClickLoadMoreProductCategory").on("click", function() {
        $("img.loading-animation-load-more").show();
        $(this).hide();
        $.ajax({
            url: "<?= base_url(); ?>products/get_more_product_category?start=" + startLoadProductCategory + "&idCat=<?= $idCat; ?>&sort=<?= $sort ?>",
            method: "get",
            success: function(response) {
                startLoadProductCategory += 12;
                console.log(response);
                if (response == "") {
                    $("#btnClickLoadMoreProductCategory").hide();
                    $("img.loading-animation-load-more").hide();
                } else {
                    $("#bodyForShowProductCategory").append(response);
                    $("img.loading-animation-load-more").hide();
                    $("#btnClickLoadMoreProductCategory").show();
                }
            }
        })
    })

    // share product
    // $(document).click(function() {
    //     $("div.wrapper div.share-dd").slideUp('fast');
    // });
    $("div.wrapper button.share").on('click', function(event) {
        $("div.wrapper div.share-dd").slideToggle('fast');
        // event.stopPropagation();
    })

    // select variant
    let variantColorProduct = "";
    let variantSizeProduct = "";
    $("button.item-option-select-variant-product-color").on('click', function() {
        $(".item-option-select-variant-product-color").css("background-color", "white");
        $(".item-option-select-variant-product-color").css("color", "black");
        $(".item-option-select-variant-product-color").css("border", "1px solid <?= $this->Settings_model->general()['navbar_color']; ?>");
        $(this).css("background-color", "<?= $this->Settings_model->general()['navbar_color']; ?>");
        $(this).css("color", "white");
        variantColorProduct = $(this).val();
    })
    $("button.item-option-select-variant-product-size").on('click', function() {
        $(".item-option-select-variant-product-size").css("background-color", "white");
        $(".item-option-select-variant-product-size").css("color", "black");
        $(".item-option-select-variant-product-size").css("border", "1px solid <?= $this->Settings_model->general()['navbar_color']; ?>");
        $(this).css("background-color", "<?= $this->Settings_model->general()['navbar_color']; ?>");
        $(this).css("color", "white");
        variantSizeProduct = $(this).val();
        $.ajax({
            url: "<?= base_url(); ?>products/change_price_by_variant",
            type: "post",
            dataType: "json",
            async: true,
            data: {
                id: '<?= $product['productId']; ?>',
                variant: variantSizeProduct
            },
            success: function(data) {
                $("div.wrapper div.top div.main-top div.ket h4.price").text(data.price);
                $("div.wrapper div.top div.main-top div.ket p.oldPrice .linet").text(data.oldPrice);
            }
        })
    })

    // function buy
    function orderNow() {
        $("p.errorMsgForColor").hide();
        $("p.errorMsgForSize").hide();
        let checkIsEmptyOrNo = false;
        const productId = '<?= $product['productId']; ?>';
        const slug = '<?= $product['slugP']; ?>';
        if ($("#hiddenColorTrueOrFalse").val() == "true" && $("#hiddenVariantTrueOrFalse").val() == "true") {
            if (variantColorProduct == "" && variantSizeProduct == "") {
                $("p.errorMsgForColor").show();
                $("p.errorMsgForSize").show();
            } else if (variantColorProduct == "") {
                $("p.errorMsgForColor").show();
            } else if (variantSizeProduct == "") {
                $("p.errorMsgForSize").show();
            } else {
                checkIsEmptyOrNo = true;
            }
        } else if ($("#hiddenColorTrueOrFalse").val() == "true") {
            if (variantColorProduct == "") {
                $("p.errorMsgForColor").show();
            } else {
                checkIsEmptyOrNo = true;
            }
        } else if ($("#hiddenVariantTrueOrFalse").val() == "true") {
            if (variantSizeProduct == "") {
                $("p.errorMsgForSize").show();
            } else {
                checkIsEmptyOrNo = true;
            }
        } else {
            checkIsEmptyOrNo = true;
        }
        if (checkIsEmptyOrNo) {
            $.ajax({
                url: "<?= base_url(); ?>cart/add_to_cart",
                type: "post",
                data: {
                    id: productId,
                    slug: slug,
                    qty: $("#qtyProduct").val(),
                    color: variantColorProduct,
                    size: variantSizeProduct
                },
                success: function(data) {
                    $("#modalCartBodyShow").html(data);
                    $('#modalCart').modal('show');
                }
            })
        }
    }

    // plus minus qty cart
    function minusProductCart(id) {
        let inputJml;
        inputJml = parseInt($(`input#qtyProductCart-${id}`).val());
        inputJml = inputJml - 1;
        if (inputJml >= 1) {
            $(`input#qtyProductCart-${id}`).val("..");
            $.ajax({
                url: "<?= base_url(); ?>cart/edit_qty_cart?type=minus",
                type: "post",
                data: {
                    rowid: id,
                },
                success: function(data) {
                    $(`#modalCartPriceProduct-${id}`).text(`Rp. ${number_format(data).split(",").join(".")}`);
                    $(`input#qtyProductCart-${id}`).val(inputJml);
                }
            })
        }
    }

    function plusProductCart(id, stock) {
        let inputJml;
        inputJml = parseInt($(`input#qtyProductCart-${id}`).val());
        inputJml = inputJml + 1;
        if (inputJml <= stock) {
            $(`input#qtyProductCart-${id}`).val("..");
            $.ajax({
                url: "<?= base_url(); ?>cart/edit_qty_cart?type=plus",
                type: "post",
                data: {
                    rowid: id,
                },
                success: function(data) {
                    $(`#modalCartPriceProduct-${id}`).text(`Rp. ${number_format(data).split(",").join(".")}`);
                    $(`input#qtyProductCart-${id}`).val(inputJml);
                }
            })
        }
    }

    function deleteCartByRowid(id) {
        $.ajax({
            url: "<?= base_url(); ?>cart/delete/" + id,
            type: "get",
            success: function(data) {
                $(`#modalCartBodyListItem-${id}`).slideUp('fast');
            }
        })
    }

    function chooseLocationFlatOngkir(el){
        let value = $(el).val();
        value = value.split("**");
        const fee = value[1];
        $("#ongkirValueOrder").val(fee);
        $("#ongkirCheckoutPage").text("Rp. " + number_format(fee).split(",").join("."));
        const price = "<?= $this->cart->total(); ?>";
        const potongan = $("#potonganCouponCheckoutPageValue").val();
        const total = parseInt(price) + parseInt(fee) + parseInt($("#uniqueCodeValueOrder").val()) - parseInt(potongan);
        $("#totalCheckoutPage").text("Rp. " + number_format(total).split(",").join("."));
    }

    let variableTempSubtotal;
    let variableTempShipping;
    let variableTempDiscount;
    let variableTempUniq;
    let variableTempTotal;

    function changeIDRToUSD() {
        if ($("#courierStatusIsAvailableCheckoutPage").val() == "true") {
            if ($("#ongkirValueOrder").val() == "0") {
                return alert("Untuk memilih PayPal harus pilih kurir dulu.")
            }
        }
        selectPaymentCheckout('8');
        $("#inputCouponCheckoutPage").prop("disabled", true);
        if ($("#inputCouponCheckoutPage").val() == "") {
            $("#msgDangerCouponWrongCheckoutPage").text("Jika ingin memasukan promo harap pilih pembayaran selain PayPal dulu, setelah itu bisa memilih PayPal lagi.")
        }
        variableTempSubtotal = $("#subTotalCheckoutPageShow").text();
        variableTempShipping = $("#ongkirCheckoutPage").text();
        variableTempDiscount = $("#potonganCouponCheckoutPageShow").text();
        variableTempUniq = $("#uniqCodeTextCheckoutPage").text();
        variableTempTotal = $("#totalCheckoutPage").text();
        const subtotal = parseInt('<?= $this->cart->total(); ?>');
        const shipping = $("#ongkirCheckoutPage").text().split(" ")[1] || "0.00";
        const discount = $("#potonganCouponCheckoutPageShow").text().split(" ")[1] || "0.00";
        const convertion = 14397;
        $("#subTotalCheckoutPageShow").text(`USD ${(subtotal/convertion).toFixed(2)}`);
        $("#ongkirCheckoutPage").text(`USD ${(parseInt(shipping.split(".").join(""))/convertion).toFixed(2)}`);
        $("#potonganCouponCheckoutPageShow").text(`USD ${(parseInt(discount.split(".").join(""))/convertion).toFixed(2)}`);
        $("#uniqCodeTextCheckoutPage").text("USD 0.00")
        const totalall = subtotal + parseInt(shipping.split(".").join("")) + parseInt(discount.split(".").join(""));
        $("#totalCheckoutPage").text(`USD ${(parseInt(totalall)/convertion).toFixed(2)}`);
    }

    function changeUSDToIDR(id) {
        selectPaymentCheckout(id);
        $("#inputCouponCheckoutPage").prop("disabled", false);
        $("#msgDangerCouponWrongCheckoutPage").text("")
        if (variableTempSubtotal) {
            $("#subTotalCheckoutPageShow").text(variableTempSubtotal);
            $("#ongkirCheckoutPage").text(variableTempShipping);
            $("#potonganCouponCheckoutPageShow").text(variableTempDiscount);
            $("#uniqCodeTextCheckoutPage").text(variableTempUniq);
            $("#totalCheckoutPage").text(variableTempTotal);
        }
    }

    function number_format(number, decimals, decPoint, thousandsSep) {
        number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
        var n = !isFinite(+number) ? 0 : +number
        var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
        var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
        var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
        var s = ''

        var toFixedFix = function(n, prec) {
            var k = Math.pow(10, prec)
            return '' + (Math.round(n * k) / k)
                .toFixed(prec)
        }

        // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
        if (s[0].length > 3) {
            s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
        }
        if ((s[1] || '').length < prec) {
            s[1] = s[1] || ''
            s[1] += new Array(prec - s[1].length + 1).join('0')
        }

        return s.join(dec)
    }

    // select2 checkout
    $("#districtCheckoutPage").select2({
        placeholder: 'Pilih Kabupaten/Kota',
        language: 'id'
    })

    $("#subdistrictCheckoutPage").select2({
        placeholder: 'Pilih kabupaten/kota dulu',
        language: 'id'
    })

    $("#districtCheckoutPage").on('change', function() {
        $("#subdistrictCheckoutPage").html(`<option</option>`)
        $("#subdistrictCheckoutPage").select2({
            placeholder: 'Loading..',
            language: 'id'
        });
        $("#courierCheckoutPage").html(`
                <option>Loading..</option>
            `);
        $("#ongkirCheckoutPage").text("Rp. 0");
        const id = $(this).val();
        $.ajax({
            url: "<?= base_url(); ?>payment/getSubdistrict",
            type: "post",
            dataType: "json",
            async: true,
            data: {
                id: id
            },
            success: function(data) {
                $("#subdistrictCheckoutPage").select2({
                    placeholder: 'Pilih Kecamatan',
                    language: 'id'
                })
                $("#subdistrictCheckoutPage").html(data);
                $("#courierCheckoutPage").html(`
                        <option>Pilih kecamatan dulu</option>
                    `);
            }
        });
    })

    $("#subdistrictCheckoutPage").on('change', function() {
        $("#courierCheckoutPage").html(`
                <option>Loading..</option>
            `);

        $("#ongkirCheckoutPage").text("Rp. 0");
        const id = $(this).val();
        $.ajax({
            url: "<?= base_url(); ?>payment/getCourier",
            type: "post",
            dataType: "json",
            async: true,
            data: {
                id: id
            },
            success: function(data) {
                $("#courierCheckoutPage").html(`
                        <option>Pilih Pengiriman</option>
                    `);
                $("#courierCheckoutPage").html(data);
            }
        });
    })

    $("#courierCheckoutPage").on("change", function() {
        let id = $(this).val();
        id = id.split('-');
        id = id[0];
        if (id === "") {
            id = 0;
        }
        const minFee = '<?= $this->Settings_model->general()['minimal_fee_cod'] ?>';
        const maxFee = '<?= $this->Settings_model->general()['maximal_fee_cod'] ?>';
        if (parseInt(id) >= parseInt(minFee) && parseInt(id) <= parseInt(maxFee)) {
            $(".logo-payment-checkout-13").show();
        }
        $("#ongkirValueOrder").val(id);
        $("#ongkirCheckoutPage").text("Rp. " + number_format(id).split(",").join("."));
        const price = "<?= $this->cart->total(); ?>";
        const potongan = $("#potonganCouponCheckoutPageValue").val();
        const total = parseInt(price) + parseInt(id) + parseInt($("#uniqueCodeValueOrder").val()) - parseInt(potongan);
        $("#totalCheckoutPage").text("Rp. " + number_format(total).split(",").join("."));
    })

    $("#btnForApplyCouponCheckoutPage").on("click", function() {
        const coupon = $("#inputCouponCheckoutPage").val();
        $("#msgDangerCouponWrongCheckoutPage").text("");
        if (coupon != "") {
            $.ajax({
                url: "<?= base_url(); ?>checkout/checkoutCoupon",
                type: "post",
                dataType: "json",
                async: true,
                data: {
                    coupon: coupon
                },
                success: function(data) {
                    console.log(data);
                    if (data.success == true) {
                        $("#potonganCouponCheckoutPageShow").text("Rp. " + number_format(data.discount).split(",").join("."));
                        $("#potonganCouponCheckoutPageValue").val(data.discount);
                        const courier = $("#ongkirValueOrder").val();
                        const price = "<?= $this->cart->total(); ?>";
                        const potongan = $("#potonganCouponCheckoutPageValue").val();
                        const total = parseInt(price) + parseInt(courier) + parseInt($("#uniqueCodeValueOrder").val()) - parseInt(potongan);
                        $("#totalCheckoutPage").text("Rp. " + number_format(total).split(",").join("."));
                    } else {
                        $("#msgDangerCouponWrongCheckoutPage").text(data.msg);
                    }
                }
            });
        }
    })

    // select payment
    function selectPaymentCheckout(id) {
        $('#msgPaymentFirstCheckoutPage').hide();
        $("#paymentSelectCheckoutPage").val("true");
        $(`#paymentLogoSelectCheckoutPageValue`).val(id);
        $(".logo-payment-checkout-page").css("border", "2px solid #ddd");
        $(".logo-payment-checkout-page").css("box-shadow", "none");
        $(`.logo-payment-checkout-${id}`).css("border", "2px solid dodgerblue");
        $(`.logo-payment-checkout-${id}`).css("box-shadow", "1px 3px 8px rgba(0, 0, 0, 0.2)");

        if (id == "13") {
            $(".list-for-fee-cod-hide").show();
            $(".list-for-uniq-code-show-first").hide();
            const totalharga = '<?= $this->cart->total() ?>';
            const ongkir = $("#ongkirValueOrder").val();
            const feeCod = '<?= $this->Settings_model->general()['fee_cod'] ?>';
            let totalall = (parseInt(totalharga) + parseInt(ongkir)) * parseInt(feeCod) / 100;
            $(".valueOfUniqCodeOrFeeCODCheckoutPage").text("Rp. " + number_format(totalall).split(",").join("."));
            const potongan = $("#potonganCouponCheckoutPageValue").val();
            const total = parseInt(totalharga) + parseInt(ongkir) + parseInt(totalall) - parseInt(potongan);
            $("#totalCheckoutPage").text("Rp. " + number_format(total).split(",").join("."));
        } else {
            $(".list-for-fee-cod-hide").hide();
            $(".list-for-uniq-code-show-first").show();
            const uniqCode = $("#uniqueCodeValueOrder").val();
            const courier = $("#ongkirValueOrder").val();
            const price = "<?= $this->cart->total(); ?>";
            const potongan = $("#potonganCouponCheckoutPageValue").val();
            const total = parseInt(price) + parseInt(courier) + parseInt(uniqCode) - parseInt(potongan);
            $("#totalCheckoutPage").text("Rp. " + number_format(total).split(",").join("."));
        }
    }

    // menu sidebar
    $("nav.navbar-top div.main-mobile .fa-bars").on("click", function() {
        $(".side-bar-menu-mobile").animate({
            left: "0"
        }, 300)
        $(".overlay-menu").animate({
            left: "0"
        }, 200)
    })
    $(".overlay-menu").on("click", function() {
        $(".side-bar-menu-mobile").animate({
            left: "-100%"
        }, 200)
        $(".overlay-menu").animate({
            left: "-100%"
        }, 300)
    })
</script>
</body>

</html>