var offset = 0;
var page = 1;
var limit = 100;
var load = true;
var sendRequest = true;
var newRequest = true;
var sort_column = "";
var sort_type = "";

$(document).ready(function(){
    var url=BASE_URL+'load-more-diamond?page=';
    if(segment1=="diamond"){
    }
    loadMoreData();
    //alert(segment1)
});



function resetForm() {
    document.getElementById("filter_form").reset();

    $(".shape-box").each(function(){
        $(this).removeClass("active");
    });
    $(".btn-box").each(function(){
        $(this).removeClass("active");
    });

    priceSliderReset();
    caratSliderReset();
}
function submitForm() {
    $("#add_data").html("");
    /*load = true;
    sendRequest = true;
    newRequest = true;
    scrollPos = 0;
    offset = 0;
    page = 1;
    limit = 100;
    sort_column = "";
    sort_type = "";
    defaultSort();*/
    loadMoreData();
}
function sortData(column,type) {
    $("#add_data").html("");
    load = true;
    sendRequest = true;
    newRequest = true;
    scrollPos = 0;
    offset = 0;
    page = 1;
    limit = 50;
    sort_column = column;
    sort_type = type;
    loadMoreData();
}

function validateInput(event) {
    var keycode = event.keyCode
    if(keycode != 46 && (keycode < 48 || keycode > 57)) {
        event.preventDefault();
    }  
}
function validateInputValue(id,index,text) {
    var from_val = $("#"+id+"_from").val();
    var to_val = $("#"+id+"_to").val();
    
    if(parseFloat(from_val) > parseFloat(to_val))  {
        notify('error','From '+text+' can not be greater than To '+text+' ');
        $("#"+id+"_to").val(from_val);
    }
}

let jsonBody = {};

const pushFilterIn = function (key, field = key) {
    const arr = [];
    $.each($("input[name='"+field+"[]']:checked"), function(){            
        arr.push($(this).val());
    });
    if(!arr.length) {
        return;
    }
    jsonBody[key] = arr.toString();
}
const pushFilterBtw = function(key, field = key) {
    const str_from = $("input[name='"+field+"_from']").val();
    let str_to = $("input[name='"+field+"_to']").val();

    if(!str_from && !str_to) {
        return;
    }

    if(field == 'carat') {
        str_to = (str_to == '6+') ? '100' : str_to;
    } else if(field == 'price') {
        str_to = (str_to == '1000000+') ? '10000000' : str_to;        
    }

    if(str_from.trim()!="" && str_to.trim()!="") {
        if(parseFloat(str_from) <= parseFloat(str_to)) {
            jsonBody[key] = str_from+"-"+str_to;
        }
    }
}

function getForm() {
    const key_to_sym_con = $("input[name='optradio']:checked").val();
    const stock = $("input[name='stock']").val();
    jsonBody = {
        stock,
        key_to_sym_con,
        page,
        limit,        
        sort_column,
        sort_type
    };
    //pushFilterIn('shape');   
  
    //pushFilterBtw('carat');   
}

$(function () {
    $("#checkAll").click(function () {
        if ($("#checkAll").is(':checked')) {
            $(".tr_checkbox").prop("checked", true);
        } else {
            $(".tr_checkbox").prop("checked", false);
        }
    });
}); 

const checkEmpty = (val) => {
    return (val != null) ? val : '';
}

const checkDisc = (val) => {
    return (val > 0) ? '+' + val : val;
}

const pagination = (totalItems) => {
    let linkHtml = '';
    let totalPages = Math.ceil(totalItems / limit);

    if(page > 1) {
        linkHtml += `<a href="javascript:void(0)" onclick="onPaging(${page - 1})">Prev</a>`;        
    }
    for (let i = 1; i <= totalPages; i++) {
        if(i <= page + 2 && i > page - 3) {
            let activeClass = (page == i) ? 'active' : '';
            linkHtml += `<a href="javascript:void(0)" class="${activeClass}" onclick="onPaging(${i})">${i}</a>`;
        }
    }
    if(page <= totalPages) {
        linkHtml += `<a href="javascript:void(0)" onclick="onPaging(${page + 1})">Next</a>`;        
    }
    document.getElementById('pagination').innerHTML = linkHtml;
}
const onPaging = (inPage) => {
    page = +inPage;

    loadMoreData();
}

function loadMoreData(){ 

    //getForm();

    var value_form = $('#form').serialize()+'&'+$.param({ "month": ''});

    $.ajax({         
        url: BASE_URL+"admin/attendance/data",
        method: "POST",
        data: value_form,
        dataType: "json",
        success: function(data){
            let html = "";
            const details = data.records; 
            const total_records = data.total; 
            const details_length = details.length;

            //pagination(total_records);

            for(let i=0; i < details_length; i++)
            {  
                html += `<tr>`;
                html += `<td>${checkEmpty(details[i].employee_id)}</td>`;
                html += `<td>${checkEmpty(details[i].name)}</td>`;
                html += `<td>${checkEmpty(details[i].email_office)}</td>`;
                html += `<td>${checkEmpty(details[i].department_name)}</td>`;
                html += `<td>${checkEmpty(details[i].total_check_in)}</td>`;
                
                html += `</tr>`;

            }

            if(newRequest) { 
                //document.getElementById('total_records').innerHTML = total_records;
            }            
            //document.getElementById('add_data').insertAdjacentHTML('beforeend',html);
            document.getElementById('add_data').innerHTML = html;
            $("#list_div").show();
            $("#filter_div").hide();

            html = '';
            // offset = parseInt(offset)+parseInt(limit);
            // limit = 50;
            load = (total_records) ? true : false;

            if(!details_length) {
                if(newRequest) { 
                    $("#sticky-button").hide();
                    $("#list_section").hide();
                    $("#no_list_section").show();
                }
            } else {
                $("#sticky-button").show();
                $("#list_section").show();
                $("#no_list_section").hide();
            }
        },
        beforeSend: function () {            
            if(newRequest) {                
                $("#loading").show();
            }
        },
        complete: function () {
            $("#loading").hide();
        }
    });
}



function print(html)
{
    //alert(html);
    var mywindow = window.open();
    mywindow.document.write('<html><head><title>print stone</title>');            
    mywindow.document.write('</head><body >');
    mywindow.document.write(html);
    mywindow.document.write('</body></html>');

    mywindow.print();
    mywindow.close();

    return true;
}

function open_windows(src)
{   
    window.open(src, "Diamond", "width=800, height=800");
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function exportList()
{
    var stock_arr = [];
    $.each($("input[name='check_stock[]']:checked"), function(){            
        stock_arr.push($(this).val());
    });
    var stock_str=stock_arr.toString();
    var stock_type = $("input[name='stock_type']").val();

    if(stock_str)
    {
        location.href=BASE_URL+'export-diamond?stock='+stock_str   
    }
    else
    {
        alertify.confirm(SITENAME, 'Do You Want To Download All Record ?', 
        function(){ 
          location.href=BASE_URL+'export-diamond?stock=&stock_type='+stock_type   
        }, 
        function(){  });                
    } 
}

