$(document).ready(function () {
    $("#editbtn").click(function () {
        $("#msgPanel").html("");//make empty error/ success message after re-edite
        var value = $('#updateSiteForm .form-cntrl').attr('disabled');
        if (value) {
            $('#updateSiteForm .form-cntrl').removeAttr('disabled');
        } else {
            $('#updateSiteForm .form-cntrl').attr('disabled', 'disabled');
        }
//        $('#siteId').attr('disabled', 'disabled');//will not update
        $(this).hide();
        $('#updatebtn').show();
    });
});

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


function msgPanel(alertType, msg) {

    return `<p class="text-${alertType}"><b>${msg}</b></p>`;
    
}


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.userLat + ", " + formdata.userLong))
        {
            feedbackMsg += "latitude or longitude is not valid.";
        }
    return feedbackMsg;
}


const addSiteURL ="../php/updateFTAdetails.php";

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");


    const formdata = {
        empId: addSiteForm.empId.value,
        siteId: addSiteForm.siteId.value,
        siteVisitDate: addSiteForm.siteVisitDate.value,
        distance: addSiteForm.distance.value,
        userLat: addSiteForm.userLat.value,
        userLong: addSiteForm.userLong.value,
        userLntAddress: addSiteForm.userLntAddress.value
    };
    //console.log(formdata);
    const feedbackMsg = validateForm(formdata);
    if (feedbackMsg === "") {
        postData(addSiteURL, formdata).then(data => {
            console.log(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);  
    }
});
;;