$(document).ready(function(){
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $('#form').change(function () {
        submitForm(); 
        // alert("hello");      
    });

    var base_url = '';
    segment_1 ='';
    var url="https://diamondapp.mydiamondsearch.com/jewelry_app/load-more-diamond"; 
	// var url=`${location.origin}/apps/proxy?shop=${Shopify.shop}`; 
    loadMoreData(url);

    
    var text_color = localStorage.getItem('text_color');
    $(".text_color").css("color", text_color);
    var font_size = localStorage.getItem('font_size');
    $(".font_size").css("font-size", font_size);
      
});

let timerId; 
const debounceFunction = (func, delay) => {
    clearTimeout(timerId);
    timerId = setTimeout(func, delay);
}

function submitForm() {
   
	// var url=`${location.origin}/apps/proxy?shop=${Shopify.shop}`;
    var url="https://diamondapp.mydiamondsearch.com/jewelry_app/load-more-diamond";
    
    loadMoreData(url);
}
function searchDelay() {
    debounceFunction(() => submitForm(), 500);
}
function pagination(argument) { 
    const url = new URL(argument);
    const urlParams = new URLSearchParams(url.search);
    const page = urlParams.get('page');
    // var urls=`${location.origin}/apps/proxy?shop=${Shopify.shop}&page=${page}`; 
    var urls=`https://diamondapp.mydiamondsearch.com/jewelry_app/load-more-diamond?shop=${Shopify.shop}&page=${page}`;
    loadMoreData(urls);
    
}
$(".form-control").keyup(function(event) {
  if(event.keyCode=='13'){
    if (event.target.value) {
      submitForm();
    }
  }
});

$(document).ready(function(){
   $("li > :checkbox").click(function(event){
    if(event.target.name == 'ex3' || event.target.name == 'ex3n') {
        searchDelay();
    } else {        
        submitForm();
    }
   });
});

 $(function () {
    $("#checkAlls").click(function () {
        if ($("#checkAlls").is(':checked')) {
            $(".tr_checkbox").prop("checked", true);
        } else {
            $(".tr_checkbox").prop("checked", false);
        }
    });
}); 
function checkInput(event) {
  
    var key = event.key;
    if(isNaN(key) && key != '.' && key != 'Enter' && key != 'Backspace' && key != 'Delete') {
        event.preventDefault();
        return false;
    }
    return true;
}

function inputValue(event,id,index,text) {
    if(checkInput(event)) {
        debounceFunction(() => inputValueDelay(id,index,text), 500);
    }
}
function inputValueDelay(id,index,text) {
    var from_val = $("#"+id+"_from").val();
    var to_val = $("#"+id+"_to").val();
    if(index && from_val.trim() == '') {
        from_val = 0;
        $("#"+id+"_from").val(0);
    }
    if(!index && to_val.trim() == '') {
        to_val = 100;
        $("#"+id+"_to").val(100);
    }

    if(parseFloat(from_val) > parseFloat(to_val)) {
        alertify.set('notifier','position', 'top-right');
        alertify.warning(text+' from can not be greater than '+text+' to ');

        $("#"+id+"_to").val(from_val);
        submitForm();
    } else if(parseFloat(from_val) >= 0 && parseFloat(to_val)) {
        submitForm();
    }
}

function showSlides(n)
{
    $(".mySlides").hide();
    // $("#easy_zoom").hide();
    $("#slides_" + n).show();
}

function loadMoreData(url_data){ 
        const dia_view = localStorage.getItem('dia_view');
        var compare_session=$("#compare_session").val();
        var text_color="";
        var compare_title="Add To Compare";

        var stock_number = $("#stock_number").val();
        var page_name = $("#page_name").val();

        var per_page=$("#per_page").val();

        var shop_name = `${Shopify.shop}`;
            // alert(shop_name);
        var value_form = $('#form').serialize()+'&'+$.param({"stock_number": stock_number, "page_name": page_name, "shop_name": shop_name, "per_page": per_page});
        localStorage.setItem('diamondForm', value_form);
        
        $.ajax({
            url: url_data,
            type: 'get',
            dataType: 'json',
            headers: {
                'Content-Type': 'application/json',
                // 'ngrok-skip-browser-warning': 'true'
            },            
            data: value_form,
            success: function(data){
                	console.log(data); 
                		console.log(data.retaillerid); 
                var details=data.records;
			// Extract variables from data.retaillerid
                    var text_color = data.retaillerid.text_color;
                    var border_color = data.retaillerid.border_color;
                    var button_background = data.retaillerid.button_background;
                    var button_text_color = data.retaillerid.button_text_color;
                    var button_background_hover = data.retaillerid.button_background_hover;
                    var button_hover_color = data.retaillerid.button_hover_color;
                    var input_bg = data.retaillerid.input_bg;
                    var body_color = data.retaillerid.body_color;
                    var heading_color = data.retaillerid.heading_color;
                    var heading_font_size = data.retaillerid.heading_font_size;
                    var primary_font_size = data.retaillerid.primary_font_size;
                    var filter_font_size = data.retaillerid.filter_font_size;
                    var sub_heading_font_size = data.retaillerid.sub_heading_font_size;
                    var primary_link_color = data.retaillerid.primary_link_color;

                    document.documentElement.style.setProperty('--text-color', text_color);
                    document.documentElement.style.setProperty('--border-color', border_color);
                    document.documentElement.style.setProperty('--button-background', button_background);
                    document.documentElement.style.setProperty('--button-text-color', button_text_color);
                    document.documentElement.style.setProperty('--button-background-hover', button_background_hover);
                    document.documentElement.style.setProperty('--button-hover-color', button_hover_color);
                    document.documentElement.style.setProperty('--input-bg', input_bg);
                    document.documentElement.style.setProperty('--body-color', body_color);
                    document.documentElement.style.setProperty('--heading-color', heading_color);
                    document.documentElement.style.setProperty('--heading-font-size', heading_font_size);
                    document.documentElement.style.setProperty('--primary-font-size', primary_font_size);
                    document.documentElement.style.setProperty('--filter-font-size', filter_font_size);
                    document.documentElement.style.setProperty('--sub-heading-font-size', sub_heading_font_size);
                    document.documentElement.style.setProperty('--primary-link-color', primary_link_color);
                
                // if (font_size) {
                //     document.documentElement.style.setProperty('--font_size_pr', font_size + 'px');
                // }
                
                // if (font_family) {
                //     document.documentElement.style.setProperty('--font_family_pr', font_family);
                // }
				
				 var html="";
                    var details_length=details.length;
                    for(i=0;i<details_length;i++)
                    {      
                        if(details[i].available_type != null){ var available_type=details[i].available_type; }else{ var available_type=""; }
                        if(details[i].center_stone_type_id != null){ var center_stone_type_id=details[i].center_stone_type_id; }else{ var center_stone_type_id=""; }
                        if(details[i].dcst_name != null){ var dcst_name=details[i].dcst_name; }else{ var dcst_name=""; }
                        if(details[i].delivery_days != null){ var delivery_days=parseFloat(details[i].delivery_days).toFixed(2); }else{ var delivery_days=""; }
                        if(details[i].design_id != null){ var design_id=details[i].design_id; }else{ var design_id="-"; }
                        if(details[i].diamond_quality_id != null){ var diamond_quality_id=details[i].diamond_quality_id; }else{ var diamond_quality_id=""; }
                        if(details[i].diamond_weight_group_id != null){ var diamond_weight_group_id=details[i].diamond_weight_group_id; }else{ var diamond_weight_group_id=""; }
						if(details[i].dqg_alias != null){ var dqg_alias=details[i].dqg_alias; }else{ var dqg_alias=""; }
                        if(details[i].dwg_name != null){ var dwg_name=details[i].dwg_name; }else{ var dwg_name=""; }
                        if(details[i].image_type != null){ var image_type=details[i].image_type; }else{ var image_type=""; }
						if(details[i].image_url != null){ var image_url=details[i].image_url; }else{ var image_url=""; }
                        if(details[i].is_build_product != null){ var is_build_product=details[i].is_build_product; }else{ var is_build_product=""; }
						if(details[i].is_new != null){ var is_new=details[i].is_new; }else{ var is_new=""; }
                        if(details[i].is_superdeals != null){ var is_superdeals=details[i].is_superdeals; }else{ var is_superdeals=""; }
						if(details[i].media_path != null){ var media_path=details[i].media_path; }else{ var media_path=""; }
                        if(details[i].product_promotion != null){ var depth= details[i].product_promotion; }else{ var product_promotion=""; }
                        if(details[i].products_blurb != null){ var products_blurb=details[i].products_blurb; }else{ var products_blurb=""; }
                        if(details[i].products_id != null){ var products_id=details[i].products_id; }else{ var products_id=""; }
                        if(details[i].products_name != null){ var products_name=details[i].products_name; }else{ var products_name=""; }
                        if(details[i].products_price != null){ var products_price=Math.round(details[i].products_price); }else{ var products_price=""; }                       
                        if(details[i].products_seo_url != null){ var products_seo_url=details[i].products_seo_url; }else{ var products_seo_url=""; }
                        if(details[i].products_style_no != null){ var products_style_no=details[i].products_style_no; }else{ var products_style_no=""; }
                        if(details[i].products_vendor_path != null){ var products_vendor_path=details[i].products_vendor_path; }else{ var products_vendor_path=""; }
                        if(details[i].vender_id != null){ var vender_id=details[i].vender_id; }else{ var vender_id=""; }
                        //const diamond_image = details[i].diamond_image || '';
                        //const diamond_video = details[i].diamond_video || '';
                        const diamondid = details[i].products_id;
                        // var shop_name = Shopify.shop ?? '';
                        var shop_name = '12cd8f-f4.myshopify.com';
                        // alert(shop_name);
                        
                        if(details[i].diamond_weight != null){ var diamond_weight=details[i].diamond_weight; }else{ var diamond_weight=""; }
                        if(details[i].diamond_quality != null){ var diamond_quality=details[i].diamond_quality; }else{ var diamond_quality=""; }

                        if(details[i].diamond_weight_min != null){ var diamond_weight_min=details[i].diamond_weight_min; }else{ var diamond_weight_min=""; }
                        if(details[i].diamond_weight_max != null){ var diamond_weight_max=details[i].diamond_weight_max; }else{ var diamond_weight_max=""; }
                        if(details[i].min_products_price != null){ var min_products_price=details[i].min_products_price; }else{ var min_products_price=""; }

                       
                        //console.log(firstElement.name);
                       // console.log(minwt);
                    
                            html +=`<div class="product_col col-sm-6 col-md-6 col-lg-4 col-xl-4 col-xxl-3 studz col-xs-12 StudActiveClass" id="stud_div_${products_name}">
         <div class="prod-list-block product_card">
            <div id="data_loader_product_variation_${products_id}" style="display: none;" align="center" class="button-loader">
               <img src="https://www.amipi.com/images/loader.gif">
            </div>
            <div id="StudMainImageDiv-${products_id}">
               <div class="CategoryProductListIMG_${products_id} prod-img product_thumb">
                  <input type="hidden" id="stud_${products_id}" name="stud_${products_id}" value="/pages/jewelry-detalis?stock_number=${products_id}">
                 
                  <a target="_blank" href="/pages/jewelry-detalis?stock_number=${products_id}" style=" cursor:pointer"> <img src="${image_url}" alt="${products_name}" title="${products_name}" class="${products_name}" id="product-variation-link-img-${products_id}" 1303="">
                  </a><a target="_blank " href="/pages/jewelry-detalis?stock_number=${products_id}">
				  <img src="${image_url}" alt="${products_name}" title="${products_name}" style="display: none;" class="CategoryProductListIMG_${products_id}" 1321=""> </a>
                  <div class="overlay" style="display: none;">
                     <div class="btm-btn"> <a class="common-btn" style="cursor:pointer;" onclick="ShowQuickViewProductBox('${products_id}','view');" title="View Details"><i class="fa fa-eye" aria-hidden="true"></i></a>
                        <a id="Product_List_WishList-${products_id}" onclick="AddToWishList('${products_id}','Product_List_');" class="wishlist-btn AddWishListClass-${products_id}" style=" cursor:pointer; " title="Add to Wishlist"> <i class="fa fa-heart-o" aria-hidden="true"></i></a> <a id="Product_List_RemoveWishList-${products_id}" onclick="RemoveFromWishList('${products_id}','Product_List_');" class="wishlist-btn-active RemoveWishListClass-${products_id}" style=" cursor:pointer;  display:none; " title="Remove From Wishlist"> <i class="fa fa-heart" aria-hidden="true"></i></a>
                        <a style=" cursor:pointer; " class="AddCompareButtClass-${products_id} wishlist-btn" onclick="Product_QV_AddToCompareFunction('${products_id}');" alt="Add To Compare" title="Compare Products"> <i class="fa fa-exchange" aria-hidden="true"></i></a>
                        <a style=" cursor:pointer; display:none;" class="RemoveCompareButtClass-${products_id} wishlist-btn-active" onclick="Product_QV_RemoveFromCompareFunction('${products_id}');" alt="Remove From Compare" title="Remove From Compare"> <i class="fa fa-exchange" aria-hidden="true"></i></a>
                     </div>
                  </div>
               </div>
            </div>
           
            <div class="product-description c_stud_product_discription">
               <p class="product-description__title  detail-three  stud-para">
                  <a id="product-title-link-${products_id}" href="/pages/jewelry-detalis?stock_number=${products_id}" target="_blank" style="cursor:pointer">
                 ${products_blurb}								</a>
                 
               </p>            
            </div>
            <!-- category and price -->
            <a id="product-variation-link-ES40" class="detail-bar product-variation-link-ES40 product-variation-detail" href="/pages/jewelry-detalis?stock_number=${products_id}" target="_blank">
            </a>
            <div class="col-xs-12 col-sm-12 product-description__price">
               <a id="product-variation-link-ES40" class="detail-bar product-variation-link-ES40 product-variation-detail" href="/pages/jewelry-detalis?stock_number=${products_id}" target="_blank">
                  <p id="product-variation-name-ES40"> ${diamond_weight_min} <span class="fw-light">to</span> ${diamond_weight_max}</p>
               </a>
               
               <a id="product-variation-link-price-ES40" class="detail-bar product-variation-link-ES40 product-variation-detail" href="/pages/jewelry-detalis?stock_number=${products_id}" target="_blank">
                  <p id="product-variation-price-ES40">$ ${min_products_price} <span class="fw-light"> & Up</span></p>
               </a>
            </div>
            
            <div class="col-xs-12 col-sm-12 product-description-variation-details d-flex justify-space-between c_stud_product-description-variation-details">
               <p id="product-variation-style-no-ES40">#${design_id}</p>
               <p id="product-variation-delivery-days-ES40" class="ship"><i class="fa fa-truck" aria-hidden="true"></i> Ships by
                  Tue, Nov 12													
               </p>
            </div>
            <div id="product-description-variation-details-action-ES40" class="c_stud_product-description-variation-details-action col-xs-12 col-sm-12 product-description-variation-details-action-ES40 stud-action-filter" style="display:none">
               <ul class="action product-d-action">
                  <li class="common-btn svg-design light-fill" 3315="">
                     <a id="product-variation-link-details-btn-ES40" href="/pages/jewelry-detalis?stock_number=${products_id}" target="_blank" title="Customize">
                        <svg id="fi_3401263" enable-background="new 0 0 512 512" height="512" viewBox="0 0 512 512" width="512" xmlns="http://www.w3.org/2000/svg">
                           <g>
                              <path d="m498.941 200.291-37.329-7.465c-4.107-13.613-9.55-26.757-16.255-39.257l21.113-31.669c3.967-5.95 3.183-13.872-1.874-18.927l-56.568-56.569c-5.056-5.056-12.978-5.84-18.927-1.875l-31.671 21.113c-12.499-6.704-25.643-12.146-39.257-16.254l-7.465-37.33c-1.401-7.011-7.558-12.058-14.708-12.058h-80c-7.15 0-13.307 5.047-14.709 12.058l-7.465 37.33c-13.614 4.108-26.758 9.551-39.257 16.254l-31.671-21.113c-5.948-3.965-13.871-3.181-18.927 1.875l-56.568 56.569c-5.057 5.056-5.841 12.978-1.874 18.927l21.113 31.669c-6.705 12.5-12.147 25.644-16.255 39.257l-37.329 7.465c-7.011 1.402-12.058 7.559-12.058 14.709v80c0 7.15 5.047 13.307 12.059 14.708l37.329 7.466c4.107 13.612 9.55 26.756 16.255 39.256l-21.113 31.67c-3.967 5.949-3.182 13.871 1.874 18.927l56.568 56.568c5.057 5.057 12.978 5.841 18.927 1.875l31.022-20.68v-94.165c-23.492-25.005-37.921-58.6-37.921-95.625 0-77.32 62.68-140 140-140s140 62.68 140 140c0 37.025-14.429 70.62-37.921 95.625v94.165l31.022 20.68c2.538 1.692 5.435 2.52 8.315 2.52 3.871 0 7.713-1.495 10.611-4.394l56.568-56.568c5.056-5.056 5.841-12.978 1.874-18.927l-21.113-31.67c6.705-12.5 12.147-25.644 16.255-39.256l37.329-7.466c7.013-1.402 12.06-7.559 12.06-14.709v-80c0-7.15-5.047-13.307-12.059-14.709z"></path>
                              <path d="m303.519 172.811c-7.549-4.373-17.127.267-18.374 8.901l-9.145 63.288h-40l-9.144-63.288c-1.248-8.634-10.825-13.274-18.374-8.901-29.289 16.965-47.482 48.459-47.482 82.189 0 36.552 20.47 69.25 53.421 85.333l1.579.771v155.896c0 8.284 6.716 15 15 15h50c8.284 0 15-6.716 15-15v-155.896l1.579-.771c32.951-16.083 53.421-48.781 53.421-85.333 0-33.73-18.193-65.224-47.481-82.189z"></path>
                           </g>
                        </svg>
                     </a>
                  </li>
                  <li 1732="" class="common-btn" style="cursor:pointer;" onclick="ProductShowShareBox('${products_id}');" title="Share With A Friend"><i class="fa fa-share-alt" aria-hidden="true"></i></li>
                  <li id="WishList-${products_id}" onclick="AddToWishList('${products_id}','');" style="cursor:pointer;" title="Add to Wishlist" class="wishlist-btn common-btn">
                     <i class="fa fa-heart" aria-hidden="true"></i>
                  </li>
                  <li style="display:none;" id="RemoveWishList-${products_id}" onclick="RemoveFromWishList('${products_id}','');" title="Remove From Wishlist" class="wishlist-btn-active common-btn">
                     <i class="fa fa-heart" aria-hidden="true"></i>
                  </li>
                  <li style=" cursor:pointer; " class="AddCompareButtClass-${products_id} wishlist-btn common-btn" onclick="Product_QV_AddToCompareFunction('${products_id}');" alt="Add To Compare" title="Add To Compare"><i class="fa fa-compress" aria-hidden="true"></i></li>
                  <li style=" cursor:pointer; display:none;" class="RemoveCompareButtClass-${products_id} wishlist-btn-active common-btn" onclick="Product_QV_RemoveFromCompareFunction('${products_id}');" alt="Remove From Compare" title="Remove From Compare"><i class="fa fa-compress" aria-hidden="true"></i></li>
                  <li class="common-btn" style="cursor:pointer;" onclick="AddToCartGridFunction('${products_id}','ES40')" title="Add To Cart"><i class="fa fa-shopping-cart" aria-hidden="true"></i></li>
               </ul>
            </div>
            <!--<span class="price"> <strong>
               $948.00 											</strong> </span>-->
         </div>
      </div>`;
                            
                            
                        
                    } 
					
					// Append the pagination links
                   // $('#pagination').html(data.page_link);

                   
                       /* $(".fa-th").css("background-color",bg_color)
                        $(".fa-list").css("background-color",'')*/
                     
                        $("#grid_diamond").show();
                        $("#grid_diamond").html(html);                    
                                    
                   // $("#total_records").html(total_records);

			},
			beforeSend: function () {
                $(".header").removeClass('sorted');
                $("#page-loader").show();
            },
            complete: function () {
                if(dia_view == 'view_as_list' && page_name == 'diamond') {
                   var table = $('#example').DataTable({
                        "retrieve": true,
                        "responsive": true,
                        "autoWidth": true,
                        "info": false,
                        "fixedHeader": true,
                        "scrollCollapse": false,
                        "paging": false,
                        "searching": false,
                        "info": false,
                        "pageLength": false,
                        "ordering": true,
                        "columnDefs": [{
                            "width": "16%",
                            "targets": [0,1,2,3,4,5]
                          }
                        ]
                      });
                   

                    // $(table.table().header()).off('click');

                    // $(table.table().header()).on('click', 'th' , function () {
                    //     if(+$(this).index() > 1) {                        
                    //         const selected_col = $(table.column( $(this).index() ).header());
                    //         if (selected_col.hasClass('sorted') && selected_col.hasClass('asc')) {
                    //             $("#sort_type").val('desc');
                    //         } else {
                    //             $("#sort_type").val('asc');                            
                    //         }
                    //         $("#sort_id").val($(this).index());
                    //         submitForm();
                    //     }                  
                    // });

                    // if ($("#sort_id").val()) {
                    //     const sorted_col = $(table.column( $("#sort_id").val() ).header());
                    //     sorted_col.addClass('sorted');
                    //     sorted_col.removeClass('asc desc').addClass($("#sort_type").val());
                    // }

                    // $('#container').css( 'display', 'block' );
                    // table.columns.adjust().draw();
                }

                $("#page-loader").fadeOut();
                // $('[data-toggle="tooltip"]').tooltip({'placement':'top'}); 
            }
		 });
}
