jQuery(document).ready(function($)
{

     //Carousel with slick slider
    $('.category-carousel').slick({
        dots: false,
        infinite: false,
        speed: 500,
        slidesToShow: 1,
        centerMode: false,
        variableWidth: true,
        slidesToScroll: 3,
        prevArrow: '<div class="category-carousel-arrow category-carousel-left"><span class="fa fa-long-arrow-left"></span></div>',
        nextArrow: '<div class="category-carousel-arrow category-carousel-right"><span class="fa fa-long-arrow-right"></span></div>'
    });
   //Bring variable products to configure.
  

 /***************************************
     *  Add to cart & Cart showing start   *
     ***************************************/
    //Bring variable products to configure layout.
    $(document).on("click",".qcld_express_v_p",function(e) {
        e.preventDefault();
        var currentDom=$(this);

        //$.magnificPopup.open({items: {src: '#qcld-express-modal-fancy'},type: 'inline'}, 0);

        $.fancybox.open( $('#qcld-express-modal-fancy'), {
            touch: false
        });
        //Change button text
        currentDom.html('<i class="fa fa-spinner" aria-hidden="true"></i>');
        var pId=$(this).attr('p-id');
        //Ajax Start for get product attributes.
        var data = {
            'action': 'get_vp_attributes',
            'p_id': pId,
            'security': qcld_express_security_nonce
        };

        jQuery.post(ajaxurl, data, function (response) {
            //Change button text
            currentDom.html('<i class="fa fa-shopping-cart" aria-hidden="true"></i>');
            $("#qcld-express-modal").html(response);
        });

    });
    

    //Variable product add to cart
    $(document).on('click','#v_p_add_to_cart',function(event) {
        event.preventDefault();

        var pId=$(this).attr('p-id');
        var quanity=$('#vPQuantity').val();
        // alert(quanity);
        var variations_id=$(this).attr('variation_id');
        var attributes=new Array();
        $.each($("#qcld-express-modal select"), function(){
            var attribute = $(this).attr('name')+'#'+ $(this).find('option:selected').text();
            attributes.push(attribute);
        });
        var data = {
            'action': 'vp_add_to_cart',
            'p_id': pId,
            'quantity': quanity,
            'variations_id':variations_id,
            'attributes':attributes,
            'security': qcld_express_security_nonce
        };

        jQuery.post(ajaxurl, data, function (response) {
            //Hide the variable product modal.
            $.fancybox.close();
            //load the newly added product to the cart
            showCart();

        });
    });

    //Add to cart for simple product.
    $(document).on("click",".qcld_express_s_p",function(e) {
        e.preventDefault();
        //Change button text

        var currentDom=$(this);
        currentDom.html('<i class="fa fa-spinner" aria-hidden="true"></i>');
    	var pId=$(this).attr('p-id');
    	var pPrice=$(this).attr('p-price');
        var qnty=$(this).closest(".qcld-express-action").find("input[name='qcld_quantity']").val();
        var data = {
            'action': 'sp_add_to_cart',
            'p_id': pId,
            'quantity': qnty,
            'p_price': pPrice,
            'security': qcld_express_security_nonce
        };

        jQuery.post(ajaxurl, data, function (response) {
            //Change button text
            currentDom.html('<i class="fa fa-shopping-cart"></i>');

            if(response=="simple"){
             $(document.body).trigger('added_to_cart');
             showCart();
            } else{
            	alert('Try again!');
            }
		});

    });


    //Show cart function
    function showCart(){
        var data = {
            'action': 'show_cart',
            'security': qcld_express_security_nonce
        };

        jQuery.post(ajaxurl, data, function (response) {
            //showing cart first
            $('.qcld-express-shop-float-cart').addClass('active-float-cart');
            $('.qcld-express-shop-right-float-cart').addClass('active-float-cart');
            //Then appending datta.
            $(".qcld-express-show-cart-data").html(response.html);
            $(".qcld-express-cart-item-num").html(response.items);
            //display the top cart as block
            $('#qcld-express-cart-container').css({'display':'block'});
            //push the body to right
            if(response.cart_mode=='float') {
                $('body').css({'margin-left': '350px', 'background': 'rgba(0,0,0,0.4)', 'transition': '0.8s'});
                qclad_express_preloader.off();
            } else if(response.cart_mode=='top'){
                $("html, body").animate({ scrollTop:100 }, 1000);
                return false;
            }
             //if on the product details fancy box display none.
            $.fancybox.close();
        });

    }



    //closs cart show
    $(document).on('click','#show-cart-close',function () {
        $('#qcld-express-cart-container').fadeOut(1500);
    });
    //Sku sorting.
    if(localStorage.getItem('sku-sort')){
        if(localStorage.getItem('sku-sort')=='sku_DESC'){
            $("#sku-sort").html('SKU <i class="fa fa-arrow-up"></i>');
        } else{
            $("#sku-sort").html('SKU <i class="fa fa-arrow-down"></i>');
        }
    }
    $("#sku-sort").on('click',function (e) {
       e.preventDefault();
      var url=$(this).attr('href');
      var paramName="product_list_order";
      if(localStorage.getItem('sku-sort')){
          if(localStorage.getItem('sku-sort')=='sku_DESC'){
              var paramSku='sku_DESC';
              localStorage.removeItem('sku-sort');
              localStorage.setItem('sku-sort','sku_ASC');
          } else{
              var paramSku= 'sku_ASC';
              localStorage.removeItem('sku-sort');
              localStorage.setItem('sku-sort','sku_DESC');
          }
      } else{
          var paramSku= 'sku_ASC';
          localStorage.setItem('sku-sort','sku_DESC');
      }
       var newUrl=replaceUrlParam(url, paramName, paramSku);
       window.location.href = newUrl;
    });
    //Title sort
    if(localStorage.getItem('title-sort')){
        if(localStorage.getItem('title-sort')=='title_DESC'){
            $("#title-sort").html('Title <i class="fa fa-arrow-up"></i>');
        } else{
            $("#title-sort").html('Title <i class="fa fa-arrow-down"></i>');
        }
    }
    //$("#title-sort").on('click',function (e) {
    $(document).on('click','#title-sort',function(e) {
        e.preventDefault();
        var url=$(this).attr('href');
        var paramName="product_list_order";
        if(localStorage.getItem('title-sort')){
            if(localStorage.getItem('title-sort')=='title_DESC'){
                var paramSku='title_DESC';
                localStorage.removeItem('title-sort');
                localStorage.setItem('title-sort','title_ASC');
            } else{
                var paramSku= 'title_ASC';
                localStorage.removeItem('title-sort');
                localStorage.setItem('title-sort','title_DESC');
            }
        } else{
            var paramSku= 'title_ASC';
            localStorage.setItem('title-sort','sku_DESC');
        }
        var newUrl=replaceUrlParam(url, paramName, paramSku);
        window.location.href = newUrl;
    });
    //Price sorting
    if(localStorage.getItem('price-sort')){
        if(localStorage.getItem('price-sort')=='price_DESC'){
            $("#price-sort").html('Price <i class="fa fa-arrow-up"></i>');
        } else{
            $("#price-sort").html('Price <i class="fa fa-arrow-down"></i>');
        }
    }
    //$("#price-sort").on('click',function (e) {
    $(document).on('click','#price-sort',function(e) {
        e.preventDefault();
        var url=$(this).attr('href');
        var paramName="product_list_order";
        if(localStorage.getItem('price-sort')){
            if(localStorage.getItem('price-sort')=='price_DESC'){
                var paramSku='price_DESC';
                localStorage.removeItem('price-sort');
                localStorage.setItem('price-sort','price_ASC');
            } else{
                var paramSku= 'price_ASC';
                localStorage.removeItem('price-sort');
                localStorage.setItem('price-sort','price_DESC');
            }
        } else{
            var paramSku= 'price_ASC';
            localStorage.setItem('price-sort','price_DESC');
        }
        var newUrl=replaceUrlParam(url, paramName, paramSku);
        window.location.href = newUrl;
    });

    function replaceUrlParam(url, paramName, paramValue){
        if(paramValue == null)
            paramValue = '';
        var pattern = new RegExp('\\b('+paramName+'=).*?(&|$)')
        if(url.search(pattern)>=0){
            return url.replace(pattern,'$1' + paramValue + '$2');
        }
        return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
    }
   //Load More
    $(document).on("click","#qcld-express-more",function(e) {
        e.preventDefault();
        var currentDom=$(this);
        var actionType="more";
        qcld_express_load_more(currentDom,actionType);
    });

  

    function qcld_express_load_more(currentDom,actionType){
        currentDom.html('<img src="'+image_loader+'" class="qcld-express-load_mores" alt="Loading.." /> Loading...');
        var offset=currentDom.attr('data-offset');
        var category_name = currentDom.attr('data-cat');
        var author= currentDom.attr('author');
        
        var data = {
            'action': 'load_more',
            'offset': offset,
            'c_id'   : category_name,
            'author' : author,
            'security': qcld_express_security_nonce
        };

        jQuery.post(ajaxurl, data, function (response) {
            currentDom.html('Load More');
            //Showing more product by appending to the list.
            $('.qcld-express-row.left-slope').remove();
            $('.qcld-express-product-container').append(response.html);
            if(response.offset==-1){
                if(actionType=='more'){
                    currentDom.css({'display':'none'});
                }else{
                    currentDom.css({'display':'none'});
                    $(window).unbind('scroll');
                }
                // $(window).unbind('scroll');
            }else{
                if(actionType=='more'){
                    currentDom.attr('data-offset',response.offset);
                } else{
                    currentDom.attr('data-offset',response.offset);
                    currentDom.css({'display':'none'});
                }
            }
            //alert(response.offset);
        });
    }


    /*****************************************
    // Category Search by ajax
    /*****************************************/
    $(document).on('click','.qcld_express_c_search',function(event) {
        event.preventDefault();

        searchPreloaders();
        var cId=$(this).attr('c-id');
        var currentDom = $(this);
        var actionType = "more";
        var offset=currentDom.attr('data-offset');
        var author=$(this).attr('author');

        var data = {
            'action': 'product_search_by_cat',
            'c_id': cId,
            'offset': offset,
            'author' : author,
            'security': qcld_express_security_nonce
        };

        jQuery.post(ajaxurl, data, function (response) {

            //$(".qcld-express-product-container").html(response.html);

            
            //$('.qcld-express-row.left-slope').remove();
            $(".qcld-express-body-content").html('');
            $(".qcld-express-product-container .header").after(response.html);
            //addCssWhenResize();
            // $('.qcld-express-more-scroll-container').hide();
             if (response.offset == -1) {
                    if (actionType == 'more') {
                        $('.qcld-express-more-scroll-container').css({'display': 'none'});
                    } else {
                        $('.qcld-express-more-scroll-container').css({'display': 'none'});
                        $(window).unbind('scroll');
                    }
                    // $(window).unbind('scroll');
                } else {
                    if (actionType == 'more') {
                        $('.qcld-express-more-scroll-container').css({'display': 'flex'});
                        $('#qcld-express-more').css({'display': 'flex'});
                        $('#qcld-express-more').attr('data-offset', response.offset);
                        $('#qcld-express-more').attr('data-cat', response.cat_type_id);
                    } else {
                        $('.qcld-express-more-scroll-container').css({'display': 'flex'});
                        $('#qcld-express-more').css({'display': 'flex'});
                        $('#qcld-express-more').attr('data-offset', response.offset);
                        $('#qcld-express-more').attr('data-cat', response.cat_type_id);
                        // currentDom.css({'display': 'none'});
                    }
                }
    

        });
    });


    // Preloader function here..
    function searchPreloaders() {
        
        //alert('working');
        show = function(){
            
            $('body').prepend('<div class="before-loading"><div class="spin" id="spin3"></div></div>');
            setTimeout(hide, 3000); 
        },

        hide = function(){
            $('.before-loading').hide();
        };
               
        show();

    };


     // category active class add and remove..
    $(document).ready(function(){
        $('.slick-slide a.qcld-express-active-category').click(function(e){
            e.preventDefault();
            $('.slick-slide a.qcld-express-active-category').removeClass("active");
            $(this).addClass("active");
        });
    });


    //Close the top cart summary
    $(document).on('click','#show-top-cart-close',function () {
        $('#qcld-express-cart-container').css({'display':'none'});
    })
    //Close the float cart summary
    $(document).on('click','#show-float-cart-close',function () {
        //$('#qcld-express-cart-container').html("");
        $('.qcld-express-shop-float-cart').removeClass('active-float-cart');
        $('body').css({'margin-left':'0px','transition': '0.8s', 'background': 'transparent'});
    });
    //To show Left floating cart
    $(document).on('click','#float-cart-btn',function () {
        //showCart();
        $('.qcld-express-shop-float-cart').addClass('active-float-cart');
        $('body').css({'margin-left':'350px','background':'rgba(0,0,0,0.4)','transition': '0.8s'});
    });

    $(document).on('keyup click','.qcld-express-simple-p-qnty',function(event) {
        var quantity = $(this).val();
        var change_value = $(this).parent().parent().find('.ajax_add_to_cart');
        var change_values = $(this).parent().parent().find('.qcld_express_s_p');
        $(change_value).attr('data-quantity', quantity);
        $(change_values).attr('data-quantity', quantity);
    });


    $(document.body).on('added_to_cart', function(){
        showCart();
    });


    $(document).on('keyup', '.qcld_express_search_products input[type="text"]', function(e) {

        var results = $('.qcld-express-live-search-results'),
        form = $('.qcld_express_search_products'),
        click = false,
        request = false;

       // results.hide();
        $('.qcld-express-live-search-results').hide();

        
        title = $(this).val();
        //alert(title);
        var author = $(this).attr('author');

        if (title.length < 2) {
            $('.qcld_express_search_products').removeClass('loading');
            return;
        }

        request && request.abort();

        request = $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                'action': 'qcld_express_shop_ajax_search',
                's': title,
                'author' : author,
                'security': qcld_express_security_nonce
            },
            dataType: 'json',
            beforeSend: function() {

                $('.qcld_express_search_products').addClass('loading');
                results.hide();
            },
            complete: function() {
                  
                $('.qcld_express_search_products').removeClass('loading');
                results.on('click', '.view-all a', function(e) {
                    e.preventDefault();
                    $('.qcld_express_search_products').parents('form').trigger('submit');
                });
                //click = true;
            },
            success: function(response) {
                $('.qcld-express-live-search-results').remove();
                $('.qcld_express_search_products').append('<div class="qcld-express-live-search-results"></div>');
                $('.qcld-express-live-search-results').html(response.html).show();
            },
            error: function() {}
        });
        
    });

    $('body').on('click', function(event) {
        if (!$(event.target).is('.qcld-express-search-form-wrapper') && $(event.target).closest('.qcld-express-search-form-wrapper').length) return;
        $('.qcld-express-live-search-results').hide();
    });


    $(document).on("click", ".qcld-express-search-single", function(event) {
        
        var p_id = $(this).attr('p-id');
        var data = {
            'action' : 'qcld_express_search_product_single_view',
            'p_id'   : p_id,
            'search_type' : 1,
            'security': qcld_express_security_nonce
        };

        jQuery.post(ajaxurl, data, function (response) {
            $(".qcld-express-product-container").html(response.html);
            $(".qcld-express-categorie a").attr("href", "#");
           
        });


    });

    setTimeout(function(){ 

        $('.qcld_minus').remove();
        $('.qcld_plus').remove();

        $('.qcld-express-simple-p-qnty').before('<span value="-" class="qcld_minus"><i class="fa fa-minus"></i></span>');
        $('.qcld-express-simple-p-qnty').after('<span value="+" class="qcld_plus"><i class="fa fa-plus"></i></span>');
    
    }, 300);


    $(document).on('click','.qcld_express_c_search, .qcld-express-search-single, #qcld-express-more',function(){
        
        setTimeout(function(){ 
            $('.qcld_minus').remove();
            $('.qcld_plus').remove();
           
            $('.qcld-express-simple-p-qnty').before('<span value="-" class="qcld_minus"><i class="fa fa-minus"></i></span>');
            $('.qcld-express-simple-p-qnty').after('<span value="+" class="qcld_plus"><i class="fa fa-plus"></i></span>');
        
        }, 2000);
      
    });



    $(document).on('click', '.qcld_plus', function(e) {
        $input = $(this).prev('input.qcld-express-simple-p-qnty');
        var val = parseInt($input.val());
        var step = $input.attr('step');
        step = 'undefined' !== typeof(step) ? parseInt(step) : 1;
        $input.val( val + step ).change();
    });
    $(document).on('click', '.qcld_minus', function(e) {
        $input = $(this).next('input.qcld-express-simple-p-qnty');
        var val = parseInt($input.val());
        var step = $input.attr('step');
        step = 'undefined' !== typeof(step) ? parseInt(step) : 1;
        if (val > 1) {
            $input.val( val - step ).change();
        } 
    });




	
});