
$(function() {
    // Header
    var prevScrollpos = window.pageYOffset;
    window.onscroll = function () {
        var currentScrollPos = window.pageYOffset;
        arr = document.getElementById("header").className.split(" ");
        if (prevScrollpos > currentScrollPos) {
            document.getElementById("header").style.top = "0";
            if (arr.indexOf("fixed") == -1) {
                document.getElementById("header").className += " " + "fixed";
            }
        } else {
            document.getElementById("header").style.top = "-50px";
            document.getElementById("header").classList.remove("fixed");
            $(".navWrapper").removeClass("show");
        }
        if (window.pageYOffset === 0) {
            document.getElementById("header").classList.remove("fixed");
            $(".navWrapper").removeClass("show");
        }
        prevScrollpos = currentScrollPos;
    };
    $(".menuBtn").click(function () {
        $(".navWrapper").toggleClass("show");
    });


    // Home Slider
    $("#homeSlider").owlCarousel({
        items: 1,
        loop: true,
        margin: 0,
        rtl: true,
        nav: true,
        mouseDrag: true,
        touchDrag: true,
        responsiveClass: true,
        autoplay : true,
        autoplayTimeout : 8000,
        autoplayHoverPause : true,
        smartSpeed : 2500,
        responsive: {
            0: {
                nav: true,
                touchDrag: true
            },
            550: {
                nav: true

            },
            900: {
                nav: true

            },
        },
    });

    $(".productCarousel").owlCarousel({
        loop: true,
        margin: 15,
        rtl: true,
        responsiveClass: true,
        autoplay : true,
        autoplayTimeout : 4000,
        autoplayHoverPause : true,
        smartSpeed : 2000,
        responsive: {
            0: {
                items: 1,
                nav: true,
            },
            550: {
                items: 2,
                nav: true,
            },
            900: {
                items: 5,
                nav: true,
                loop: true,
            },
        },
    });




    $(".brandCarousel").owlCarousel({
        loop: true,
        margin: 15,
        rtl: true,
        responsiveClass: true,
        autoplay : true,
        autoplayTimeout : 4000,
        autoplayHoverPause : true,
        smartSpeed : 2000,
        responsive: {
            0: {
                items: 1,
                nav: true,
            },
            550: {
                items: 2,
                nav: true,
            },
            900: {
                items: 8,
                nav: true,
                loop: true,
            },
        },
    });









    $(".executorCarousel").owlCarousel({
        loop: true,
        margin: 3,
        rtl: true,
        responsiveClass: true,
        autoplay : true,
        autoplayTimeout : 8000,
        autoplayHoverPause : true,
        smartSpeed : 5500,
        responsive: {
            0: {
                items: 1,
                nav: true,
            },
            550: {
                items: 2,
                nav: true,
            },
            900: {
                items: 3,
                nav: true,
                loop: true,
            },
        },
    });

    $(".profileClubSlider").owlCarousel({
        loop: false,
        margin: 1,
        rtl: true,
        responsiveClass: true,
        autoplay : true,
        autoplayTimeout : 8000,
        autoplayHoverPause : true,
        smartSpeed : 5500,
        responsive: {
            0: {
                items: 1,
                nav: true,
            },
            550: {
                items: 1,
                nav: true,
            },
            900: {
                items: 1,
                nav: true,
                loop: false,
            },
        },
    });

    $(".historyProductCarousel").owlCarousel({
        loop: true,
        margin: 10,
        rtl: true,
        responsiveClass: true,
        responsive: {
            0: {
                items: 1,
                nav: true,
            },
            550: {
                items: 2,
                nav: true,
            },
            900: {
                items: 3,
                nav: true,
                loop: true,
            },
        },
    });

    var wow = new WOW({
        boxClass: "wow", // animated element css class (default is wow)
        animateClass: "animated", // animation css class (default is animated)
        offset: 0, // distance to the element when triggering the animation (default is 0)
        mobile: false, // trigger animations on mobile devices (default is true)
    });
    wow.init();

    //Get the button:
    topTop = document.getElementById("scrollTop");

    // When the user scrolls down 20px from the top of the document, show the button
    window.onscroll = function () {
        scrollFunction();
    };

    //Set Profile Percent
    if ($("#profileProgress").length > 0) {
        setDatePicker();
    }

    // Set Date Picker
    if ($(".observer-example").length > 0) {
        progressSet();
    }
    windowSize();
    if($(".specServiceWrapper").length > 0){
        productCarousel();
    }
    $(window).on('resize', function() {
        windowSize();
        if($(".specServiceWrapper").length > 0){
            productCarousel();
        }
    });

    // CountDown
    if($(".countdown").length > 0){
        countDown();
    }

    // Show And Hide Cart Preview
    $("#cartView").mouseover(function(){
        $(".cartPreview").addClass("show");
    });

    $("#cartView").click(function(){
        $(".cartPreview").addClass("show");
    });

    $( "#cartView" ).mouseleave(function() {
        var isOnCart = false;

        $(".cartPreview").mouseenter(function(){
            isOnCart=true;
        });

        $(".cartPreview").mouseleave(function(){
            isOnCart=false;
        });
        setTimeout(function(){
            if(isOnCart){
            }else{
                $(".cartPreview").removeClass("show");
            }
        },100);
    });
    $( ".cartPreview" ).mouseleave(function() {
        $(".cartPreview").removeClass("show");
    });

    // Select2
    if($('select').length > 0){
        $('select').select2();
    }

    setTimeout(function(){
        hideLoading();
    },1500)

});

$(document).mouseup(function(e) {
    var container = $(".cartPreview");
    if (!container.is(e.target) && container.has(e.target).length === 0)
    {
        container.removeClass("show");
    }
});
$(function () {
    //usage
    $(".usage").persianDatepicker();




});

function scrollFunction() {
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
        topTop.style.display = "block";
    } else {
        topTop.style.display = "none";
    }

    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
        $(".cartPreview").removeClass("show");
        $(".navWrapper").removeClass("show");
        $("#header").addClass("fixed");
    }else{
        $("#header").removeClass("fixed");
    }
}

// When the user clicks on the button, scroll to the top of the document
function scrollToTop() {
    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}

// Video Play Pause
$(".sellerIntroVideo").on("click", function (e) {
    if ($(".sellerIntroVideo").find("video").get(0).paused) {
        $(".sellerIntroVideo").find("video").get(0).play();
        $(".sellerIntroVideoBtn").addClass("hidden");
    } else {
        $(".sellerIntroVideo").find("video").get(0).pause();
        $(".sellerIntroVideoBtn").removeClass("hidden");
    }
    e.preventDefault();
});

// Add New Address
$("#addAddress").click(function ()
{
    $(".addNewAddressWrapper").slideToggle();
    var new_type='';
    var type_reg = $("#adres_reg_type").val();
    if(type_reg == 1)
    {
        new_type=2;
    }
    else
    {
        new_type=1;
    }
    $("#adres_reg_type").val(new_type);
});

// Other Transferee
$("#transfereeAdd").change(function () {
    let val = parseInt($(this).val());
    if (val == 1) {
        $(".transfereeDetail").slideDown();
    } else {
        $(".transfereeDetail").slideUp();
    }
});

// GateWay Select
$("input[name='gateWaySelect']").change(function () {
    $(".orderPrevGateway").find(".form-group").removeClass("active");
    $(this).parent(".form-group").addClass("active");
});

// Cart Increase

function incCount(elem) {
    let val = parseInt($(elem).parents(".tProdCount").find("input").val());
    val = val + 1;
    $(elem).parents(".tProdCount").find("input").val(val);
}

function decCount(elem) {
    let val = parseInt($(elem).parents(".tProdCount").find("input").val());
    if (val <= 1) {
        $(elem).parents(".tProdCount").find("input").val("1");
    } else {
        val = val - 1;
        $(elem).parents(".tProdCount").find("input").val(val);
    }
}


function progressSet() {
    let percent = parseFloat(jQuery("#profileProgress").data("percent"));
    var bar = new ProgressBar.Circle(profileProgress, {
        color: "#333",
        // This has to be the same size as the maximum width to
        // prevent clipping
        strokeWidth: 10,
        trailWidth: 1,
        easing: "easeInOut",
        duration: 2400,
        text: {
            autoStyleContainer: false,
        },
        from: { color: "#00ddf7", width: 7 },
        to: { color: "#16e88d", width: 7 },
        // Set default step function for all animate calls
        step: function (state, circle) {
            circle.path.setAttribute("stroke", state.color);
            circle.path.setAttribute("stroke-width", state.width);

            var value = Math.round(circle.value() * 100) + " %";
            if (value === 0) {
                circle.setText("");
            } else {
                circle.setText(value);
            }
        },
    });
    bar.text.style.fontSize = "1.1rem";

    bar.animate(percent / 100);
}

function setDatePicker() {
    $(".observer-example").persianDatepicker({
        observer: true,
        format: 'YYYY/MM/DD',
        altField: '.observer-example-alt',
        autoClose: true
    });
}

$(".profileTabMenu > i").click(function () {
    $(".profileTabMenu").find(".nav-tabs").toggleClass("heightShow");
});

//Product Menu
$(".searchSelects").click(function () {
    $(".menu").toggleClass("show");
    $(".searchSelects").toggleClass("show");
});

function clicksrchm()
{
    $(".menu").toggleClass("show");
    $(".searchSelects").toggleClass("show");
    console.log("rfv");
}

//Product mobile Menu
$(".searchBar").click(function () {
    $(".menumobile_e").toggleClass("show");
    $(".searchBar").toggleClass("show");
});

// Product Menu Close
window.onload = function () {
    document.onclick = function (e) {
        if (e.target.id !== "menu" && e.target.id !== "productMenu") {
            $("#menu").removeClass("show");
            $(".searchSelects").removeClass("show");
        }
    };
};




// Copy Link to Clipboard
function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    let link = $(element).attr("data-url");
    $temp.val(link).select();
    document.execCommand("copy");
    $(element).parents(".prodShare").find("p").show();
    setTimeout(function () {
        $(element).parents(".prodShare").find("p").hide();
    }, 2000);
    $temp.remove();
}

//Price Change
function changePriceFrom(val,paging) {
    $("#progmin").html(parseInt(val).toLocaleString());
    $(".fromPriceWrapper > label > span").html(parseInt(val).toLocaleString());
    shoplist(paging);


}

function changePriceTo(val,paging) {
    $("#progmax").html(parseInt(val).toLocaleString());
    $(".toPriceWrapper > label > span").html(parseInt(val).toLocaleString());
    shoplist(paging);

}





// Shop Filter Mobile
$(".filterMobBtn").click(function () {
    
    if($(this).find("i").hasClass("fa-filter")){
        $(".filterListWrapper").addClass("show");
        $(this).find("i").removeClass("fa-filter");
        $(this).find("i").addClass("fa-times");
    }else{
        $(".filterListWrapper").removeClass("show");
        $(this).find("i").removeClass("fa-times");
        $(this).find("i").addClass("fa-filter");
    }
//  if($(".main-content").hasClass("show")){

//  }else{


//  }
});




// Shop Sticky Sider Bar

if($(".theiaStickySidebar").length > 0){
    $(".shopProducts, .shopSideBar").theiaStickySidebar({
        // Settings
        additionalMarginTop: 30,
        minWidth: 769,
    });
}



// Realated Products
$(".realatedProductsCarousel").owlCarousel({
    loop: true,
    margin: 5,
    rtl: true,
    autoplay : true,
    autoplayTimeout : 4000,
    autoplayHoverPause : true,
    responsiveClass: true,
    responsive: {
        0: {
            items: 1,
            nav: true,
        },
        550: {
            items: 2,
            nav: true,
        },
        900: {
            items: 4,
            nav: true,
            loop: true,
        },
        1200: {
            items: 5,
            nav: true,
            loop: true,
        },
    },
});

// Product Color Select
$("input[name='colorSelect']").change(function () {
    $(".prodColor").find(".form-group").removeClass("active");
    $(this).parent(".form-group").addClass("active");
});

//Check Window Size
function windowSize(){
    var width = $(window).width();
    width = $(this).width();
    if(width < 769){
        if( $(".shopContent").length > 0){
            $(".shopContent").find(".main-content").addClass("show");
        }
    }else{
        if( $(".shopContent").length > 0){
            $(".shopContent").find(".main-content").removeClass("show");
        }
    }
}


function productCarousel() {
    var checkWidth = $(window).width();
    var owlPost = $(".specServiceWrapper").find(".row").first();
    if (checkWidth > 550) {
        if (typeof owlPost.data('owl.carousel') != 'undefined') {
            owlPost.data('owl.carousel').destroy();
        }
        owlPost.removeClass('owl-carousel owl-theme');
    } else if (checkWidth < 551) {
        owlPost.addClass('owl-carousel owl-theme');
        owlPost.owlCarousel({
            items: 1,
            rtl: true,
            slideSpeed: 2500,
            animateOut: 'fadeOut',
            autoplay: true,
            autoplayTimeout : 6000,
            autoplayHoverPause : true,
            smartSpeed : 4000,
            dots: false,
            nav:true,
            loop: true
        });
    }
}




function isScript(src){
    var scripts = document.getElementsByTagName("script");
    for(var i = 0; i < scripts.length; i++)
        if(scripts[i].getAttribute('src') == src) return true;
    return false;
}


// Shop Filter Search
$(".filterSearch").find("input").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $(this).parents(".filteringDivs").find(".form-check").filter(function() {
        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
});


function removeCartItem(marker,conter,id){
    var title_per='';
    var url_per='';
    if(marker=='product')
    {
        title_per = 'آیا از حذف این محصول از سبد اطمینان دارید؟';
        url_per = 'action/removetobasket.php';

    }
    else if(marker=='product_prv')
    {
        title_per = 'آیا از حذف این محصول از سبد اطمینان دارید؟';
        url_per = '../action/removetobasket.php';

    }
    else if(marker == 'cart')
    {
        title_per = 'آیا از حذف این محصول از سبد اطمینان دارید؟';
        url_per = 'action/removetocart.php';
    }
    Swal.fire({


        title: title_per,
        icon : 'question',
        showDenyButton: true,
        confirmButtonText: `بله`,
        denyButtonText: `خیر`,
    }).then((result) =>
    {
        if (result.isConfirmed)
        {
            if(marker=='product')
            {
                $.ajax({

                    url : url_per,
                    method : 'POST',
                    data : {
                        id_cart : id
                    },
                    dataType: 'json',
                    statusCode : {
                        404 : function () {
                            alert("خطا در اتصال");
                        }
                    },
                    success :  function (data) {

                        var step=data.stepp;
                        var stepproo=data.stepPro;
                        var array_div=data.array_div;
                        var total_price=data.total_price;
                        var id_product_return=data.id_product_return;
                        var tedad_basket=data.tedad_basket;
                        var id_prf=data.id_prf;


                        $("#td_price_totall").html(total_price);

                        if(window.location.pathname == '/product.php')
                        {
                            $('.btn_addc'+id_product_return+'prfr'+id_prf).text("افزودن به سبد");
                        }
                        else
                        {
                            if(id_prf == '0')
                            {
                                $('.btn_addc'+id_product_return+'prfr0').removeClass("showCartBtn");
                            }
                            else
                            {
                                // $('.btn_addc'+id_product_return+'prfr'+id_prf).text("انتخاب");
                            }
                        }

                        $('.inp'+id_product_return+'pfg'+id_prf).val(stepproo);
                        // $("#product-quantity").val(stepproo);
                        $(".counter_basket").text(tedad_basket);


                        if(parseInt(tedad_basket) >= 5)
                        {
                            var heightbasket=350;
                        }
                        else
                        {
                            var heightbasket = parseInt(tedad_basket)*70;
                        }
                        $(".cartPreviewList").css("height",heightbasket+"px");


                        Swal.fire('محصول با موفقیت حذف شد', '', 'success');
                        $("#x"+conter).remove();
                        let newvalcoicraute=parseInt(conter)+1;
                        $("#y"+newvalcoicraute).remove();


                    }

                });
            }
            else  if(marker=='product_prv')
            {
                $.ajax({

                    url : url_per,
                    method : 'POST',
                    data : {
                        id_cart : id
                    },
                    dataType: 'json',
                    statusCode : {
                        404 : function () {
                            alert("خطا در اتصال");
                        }
                    },
                    success :  function (data) {

                        var step=data.stepp;
                        var array_div=data.array_div;
                        var total_price=data.total_price;
                        var id_product_return=data.id_product_return;
                        var tedad_basket=data.tedad_basket;
                        var id_prf=data.id_prf;


                        $("#td_price_totall").html(total_price);

                        if(window.location.pathname == '/product.php')
                        {
                            $('.btn_addc'+id_product_return+'prfr'+id_prf).text("افزودن به سبد");
                        }
                        else
                        {
                            if(id_prf == '0')
                            {
                                $('.btn_addc'+id_product_return+'prfr0').removeClass("showCartBtn");
                            }
                            else
                            {
                                // $('.btn_addc'+id_product_return+'prfr'+id_prf).text("انتخاب");
                            }
                        }

                        $("#product-quantity").val(step);
                        $(".counter_basket").text(tedad_basket);


                        if(parseInt(tedad_basket) >= 5)
                        {
                            var heightbasket=350;
                        }
                        else
                        {
                            var heightbasket = parseInt(tedad_basket)*70;
                        }
                        $(".cartPreviewList").css("height",heightbasket+"px");


                        Swal.fire('محصول با موفقیت حذف شد', '', 'success');
                        $("#x"+conter).remove();
                        let newvalcoicraute=parseInt(conter)+1;
                        $("#y"+newvalcoicraute).remove();


                    }

                });
            }
            else if(marker=='cart')
            {
                $.ajax({

                    url : url_per,
                    method : 'POST',
                    data : {
                        id_cart : id
                    },
                    dataType: 'json',
                    statusCode : {
                        404 : function () {
                            alert("خطا در اتصال");
                        }
                    },
                    success :  function (data) {

                        var messa = data.mess;
                        window.location.href = 'checkout.php';


                    }

                });
            }
            



        }
        else if (result.isDenied)
        {
        // cancel function
        }
    })
}

// Add Couppon
function useCouponPay(){
    Swal.fire({
        icon: 'success',
        title: 'کد تخفیف با موفقیت اعمال شد',
        showConfirmButton: false,
        timer: 1500
    })
}

// Pay by Wallet
function payByWallet(){



    Swal.fire({
        icon: 'success',
        title: 'مبلغ اعتبار از پرداختی شما کسر شد',
        showConfirmButton: false,
        timer: 1500
    })
}

// Check Phone Before Send Sms
function checkPhone(elem){
    let phone = $(elem).siblings("input[name=phoneNumber]").val();
    if($.trim(phone).length > 0){
        Swal.fire({
            title: 'آیا از صحت شماره موبایل خود مطمئن هستید؟ ' + phone,
            icon : 'question',
            showDenyButton: true,
            confirmButtonText: `بله`,
            denyButtonText: `تغییر شماره`,
        }).then((result) => {
            if (result.isConfirmed) {
            // ok function
        } else if (result.isDenied) {
            // cancel function
        }
    })
    }else{
        Swal.fire({
            icon: 'warning',
            title: 'لطفا شماره موبایل را وارد کنید',
            showConfirmButton: false,
            timer: 1500
        })
    }
}

// CountDown
function countDown(time,marker,mobile){
    var timer2 = "1:30";
    if(time)
    {
        timer2 = time;
    }
    var interval = setInterval(function()
    {
        var timer = timer2.split(':');
        //by parsing integer, I avoid all extra string processing
        var minutes = parseInt(timer[0], 10);
        var seconds = parseInt(timer[1], 10);
        --seconds;
        minutes = (seconds < 0) ? --minutes : minutes;
        if (minutes < 0)
        {
            clearInterval(interval);
            $(".countdown").text(0);
            $("#again_div").css('display','inline-block');
            var string = marker+'#*#'+mobile;
            send_request_ajax_json(string).done(function (data)
            {

            })
        }

        seconds = (seconds < 0) ? 59 : seconds;
        seconds = (seconds < 10) ? '0' + seconds : seconds;
        //minutes = (minutes < 10) ?  minutes : minutes;
        $('.countdown').html(minutes + ':' + seconds);




        timer2 = minutes + ':' + seconds;
        if(minutes == 0 && seconds == 0){
            $('.countDownWrapper').html("").fadeOut();

        }
    }, 1000);

}

// Show Sub Menu By Click

$(".hasSubSubMenu").click(function(){
    var width = $(window).width();
    if(width < 770){
        $(this).toggleClass("show");
        return false;
    }
});

$(".hasSubMenu").click(function(){
    var width = $(window).width();
    if(width < 770){
        $(this).toggleClass("show");
        return false;
    }
});


// Inc & Dec Product Count

function incCountQuent(elem){

    let valueCrtn=1;
    let tickCrtn = $("#tick_carton").val();
    if(parseInt(tickCrtn)==1)
    {
        valueCrtn = parseInt($("#value_carton").val(),10);
    }


    let val = parseInt($(elem).parents(".prodAddToCartCount").find("input").val());
    val = val + valueCrtn;
    $(elem).parents(".prodAddToCartCount").find("input").val(val);
}

function decCountQuent(elem)
{

    let valueCrtn=1;
    let tickCrtn = $("#tick_carton").val();
    if(parseInt(tickCrtn)==1)
    {
        valueCrtn = parseInt($("#value_carton").val(),10);
    }



    let val = parseInt($(elem).parents(".prodAddToCartCount").find("input").val());
    if (val <= 1) {

        $(elem).parents(".prodAddToCartCount").find("input").val(parseInt(valueCrtn));
    } else {
        val = val - parseInt(valueCrtn);
        if(parseInt(tickCrtn)==1 && val==0)
        {
            $(elem).parents(".prodAddToCartCount").find("input").val(valueCrtn);
        }
        else
        {
            $(elem).parents(".prodAddToCartCount").find("input").val(val);
        }


    }
}


function showLoading(){
    if( $(".loadingWrapper").length > 0){
        // $(".loadingWrapper").fadeIn();
    }
}

function hideLoading(){
    if( $(".loadingWrapper").length > 0){
        // $(".loadingWrapper").fadeOut();
    }
}

