var offset = 0;
var limit = 100;
var load = true;
var sendRequest = true;
var newRequest = true;
var isSubmit = false;
//var isJewleryDetails = false;
var sort_column = "";
var sort_type = "";
var last_scroll = "";
let dataArray = [];
let jsonBody = {};
let dataImg = [];
let dataVideo = [];

$(document).ready(function(){
    detailOpen(segment2);
});

$(".enter_key").keyup(function(event) {
  if(event.keyCode=='13'){
    jewelryVariation()
  }
});

const closeList = (e) => {
    e.closest('.dropdown').classList.remove('open');
}
$(".dropdown-menu").click(function(e){
    e.stopPropagation();
});

const urlSegment = (segment) => {
    if(!segment) { return; }

    const pathname = window.location.href.replace(base_url, "").split("/");
    return pathname[segment-1];
}

const checkEmpty = function (val, isReturn = '') {
    return (val != null && val != "" && val != " ") ? val : isReturn;
}

function certOpen(REPORT_NO) {
    window.open(`https://dnalinks.in/certificate_Images/${REPORT_NO}.pdf`,'_blank');
}
function dnaOpen(PACKET_NO) {
    window.open(`https://dna.dnalinks.in/j/${PACKET_NO}`,'_blank');
}
function imgOpen(PACKET_NO) {
    return;

    const img = `<img src="https://dnalinks.in/${PACKET_NO}.jpg" onerror="imgError(this)">`;

    $("#image-body").html(img);
    $("#image-modal").modal("show");
}

function detailOpen(id) {
    $.ajax({             
        url: APIURL+'/media',
        method: "POST",
        data: JSON.stringify({ 'item' : id}),
        dataType: "json",
        success: function(data){
            dataImg = data.media.dataImg;
            dataVideo = data.media.dataVideo;

            variationImage(varMetalColor);   
        }
    });        
}

function detailClose() {
    window.close();
}

//---------------------------------------------------------------------------
const pushFilterEq = function (key, field = key) {
    const value = $("input[name='"+field+"']:checked").val() || '';

    jsonBody[key] = value;
}

function getForm() {
    const ring_size = document.getElementById('ring_size').value || '';
    jsonBody = {
        'item': segment2,
        'ringSize': ring_size
    };
    pushFilterEq('metalType', 'metal');
    pushFilterEq('diaQuality', 'dia_quality');
    pushFilterEq('ctWeight', 'ct_weight');
    pushFilterEq('diaShape', 'dia_shape');
}

function jewelryVariation(filterName) {
    getForm();

    $.ajax({         
        url: APIURL+"/variation",
        method: "POST",
        data: JSON.stringify(jsonBody), 
        headers: {
            "Accept": "*/*",
            "Content-Type": "application/json",
        },
        dataType: "json",
        success: function(data){
            const details = data.record[0]; 

            if(filterName == 'metal') {
                variationImage(details.metal_color);                
            }
            
            const remarks = checkEmpty(details.remarks);
            const selling_price = checkEmpty((details.selling_price)) ? Math.round(details.selling_price) : '';  
            $("#price").html(selling_price);   
            $("#remarks").html(remarks); 
            $("#pro_id").val(details.pro_id); 

            let html = ``;
            
            varDetail.forEach((val, index ) => {
                if(details[val.column]) {
                    let value = (val.column == 'section') ? details.jew_type + ' ' : '';
                    value += (val.column == 'metal_type') ? details.metal_type.replace('K', '') : details[val.column];

                    html += `<div class="col-detail">      
                            <div class="key">${val.name}:</div> 
                            <div class="value">${value}</div> 
                        </div>`;
                }
            });  

            $("#pro-detail").html(html);   

            const stateObj = { id: 1 };
            history.pushState(stateObj, "", `${base_url}j/${segment2}?id=${details.pro_id}`);
            
        },
        beforeSend: function () {
            //$("#loading").show();
        },
        complete: function () {
            //$("#loading").hide();
        }
    });
    
}

const variationImage = (metalColor) => {
    if(!metalColor) {
        return;
    }
    const imgArr = dataImg.filter(val => val.includes(metalColor+'.jpg'));
    const vidArr = dataVideo.filter(val => val.includes(metalColor+'.mp4'));

    const thumbArr = [];
    imgArr.forEach((val, index) => {        
        thumbArr.push(`<div class="swiper-slide"><img src="${val}" /></div>`);
    });
    vidArr.forEach((val, index) => {
        thumbArr.push(`<div class="swiper-slide">${svgVideo}</div>`);
    });

    const swiperMainArr = [];
    imgArr.forEach((val, index) => {
        swiperMainArr.push(`<div class="swiper-slide"><div class="swiper-zoom-container"><img src="${val}" loading="lazy" /></div>
                 <div class="swiper-lazy-preloader swiper-lazy-preloader-white"></div></div>`);
    });
    vidArr.forEach((val, index) => {
        swiperMainArr.push(`<div class="swiper-slide"><video autoplay muted loop> <source src="${val}" type="video/mp4"></video> </div>`);
    });

    const mediaLength = imgArr.length + vidArr.length;

    let thumbLength = mediaLength;
    if(mediaLength < 4) {
        thumbLength = 4;
    } else if(mediaLength > 8) {
        thumbLength = 8;
    }

    const swiperThumb1 = document.querySelector('.mySwiper').swiper;    
    const swiperMain1 = document.querySelector('.mySwiper2').swiper;

    if(swiperThumb1 && swiperMain1) {
        swiperThumb1.destroy(false, true);
        swiperMain1.destroy(false, true);        
    }

    const swiperThumb = new Swiper(".mySwiper", {
        loop: true,
        spaceBetween: 10,
        direction: "vertical",
        slidesPerView: thumbLength,
        freeMode: true,
        watchSlidesProgress: true
    });
    const swiperMain = new Swiper(".mySwiper2", {
        zoom: true,
        loop: true,
        spaceBetween: 10,
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
        thumbs: {
            swiper: swiperThumb,
        },
    });

    swiperThumb.removeAllSlides();
    swiperMain.removeAllSlides();
    swiperThumb.appendSlide(thumbArr);
    swiperMain.appendSlide(swiperMainArr);4

    swiperMain.slideTo(0, 0, false);
    // swiperThumb.update();
    // swiperMain.update();
    // ---------------------------------------------------------------

    const scrollableDiv = document.getElementById('mySwiperScroll');
    const scrollLeftBtn = document.getElementById('scroll-left-btn');
    const scrollRightBtn = document.getElementById('scroll-right-btn');

    if(mediaLength) {
        scrollLeftBtn.addEventListener('click', () => {
            scrollableDiv.scroll({
              top: scrollableDiv.scrollTop - 400,
              behavior: 'smooth'
            });
        });

        scrollRightBtn.addEventListener('click', () => {
            scrollableDiv.scroll({
              top: scrollableDiv.scrollTop + 400,
              behavior: 'smooth'
            });
        });          
    }

    if(mediaLength < 8) {
        scrollLeftBtn.classList.add("hide");
        scrollRightBtn.classList.add("hide");
    }
}
//---------------------------------------------------------------------------

function imgError(e) {
    e.parentElement.href = '#';
    e.src = base_url+'assets/images/No_image.jpg?v=17042023';
}


function open_windows(src) {   
    window.open(src, "Watch", "width=800, height=800");
}
//---------------------------------------------------------------------------

function emailUs() {

    $("#email_modal").modal('show');
}

function emailUsSubmit() {
    getForm();

    const price = $("#price").text(); 
    const proId = $("#pro_id").val(); 

    // const name = $("#name").val(); 
    const email = $("#email").val(); 
    const inscription = $("#inscription").val(); 
    const remarks = $("#user_remarks").val(); 

    if(!email) {
        $("#email").addClass('border-red');
        return;
    }
    $("#email").removeClass('border-red');

    jsonBody.price = +price;
    jsonBody.proId = proId;
    jsonBody.remarks = remarks;
    // jsonBody.name = name;
    jsonBody.email = email;
    jsonBody.inscription = inscription;

    $.ajax({
        url: base_url+'jewelry-email',
        data: JSON.stringify(jsonBody),   
        dataType: 'json',
        type: 'post',            
        headers: {
            "Content-Type": "application/json",
        },                                         
        success: (data) => {
            alert(data.message);
            $("#email_modal").modal('hide');
        }
    });  
}

//---------------------------------------------------------------------------

const svgVideo = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-camera-video-fill" viewBox="0 0 16 16">
                                <path fill-rule="evenodd" d="M0 5a2 2 0 0 1 2-2h7.5a2 2 0 0 1 1.983 1.738l3.11-1.382A1 1 0 0 1 16 4.269v7.462a1 1 0 0 1-1.406.913l-3.111-1.382A2 2 0 0 1 9.5 13H2a2 2 0 0 1-2-2V5z"></path>
                            </svg>`;