//

var C_JOB_CENTRE_FILTER       = "401";
var C_UPDATE_JOB_CENTRE_VIEW  = "403";
var C_DOWNLOAD_ATTACHMENT     = "407";
var C_DELETE_ATTACHMENT       = "408";
var C_SHOW_UPLOAD_ATTACH_VIEW = "409";
var C_SHOW_UPLOAD_ATTACH_DOC  = "410";
var C_SHOW_SAVE_ATTACHMENT    = "411";
var C_CANCEL_ATTACHMENT       = "412";
var C_DELETE_JOB_CENTRE       = "413";
var C_SHOW_UTILIZATION        = "414";
var C_SHOW_UTILIZATION_REPORT = "415";
var C_SHOW_ASSIGNMENT_LIST_VIEW  = "416";
var C_SHOW_JOB_PLAN_REPORT       = "417";
var C_SERVICE_PLAN_PRINT_PREVIEW = "418";

var C_ACCOUNT_MANAGER               = "1";
var C_PROJECT_MANAGER               = "2";
var C_TECHNICAL_CONSULTANT          = "3";
var C_APPLICATION_CONSULTANT        = "4";
var C_DEVELOPER                     = "5";
var C_CUST_PROJECT_SPONSOR          = "6";
var C_CUST_PROJECT_ADVISOR          = "7";
var C_CUST_PROJECT_MANAGER          = "8";
var C_CUST_PROJECT_MEMBER           = "9";

var job_quotation_idx = 1000;
var jobcentre_obj = null ;
var jobassign_obj = null ;
var img_idx      = 0;

var acc_mgr_idx             = 0;
var proj_mgr_idx            = 0;
var tech_cons_idx           = 0;
var app_cons_idx            = 0;
var dev_idx                 = 0;
var cust_proj_sponsor_idx   = 0;
var cust_proj_advisor_idx   = 0;
var cust_proj_manager_idx   = 0;
var cust_proj_member_idx    = 0;

$(document).ready(function() {

});

function changeJobPlanTempOption() {
    if($('#chkJobPlanTempOption').is(':checked')){
        $('#divJobPlanTemplateList').hide();
        $('#divJobPlanTemplateName').show();

        $('#txtChkJobPlanTempOption').val("1");
    }else{
        $('#divJobPlanTemplateList').show();
        $('#divJobPlanTemplateName').hide();

        $('#txtChkJobPlanTempOption').val("0");
    }

    populateJobPlanTemplateList();
}

function showContentIndex(html) {
    if(screen_index == 0 ){
        $("#screen_container").html(html);
    
    }else{

        /**hide the previous index */
        $('#screen'+(screen_index-1)+'').hide();
        
        /**fill the index-1a or the next screen with HTML from controller */
        $('#screen'+(screen_index-1)+'a').html(html);
        /**show the main power */
        $('#screen'+(screen_index-1)+'a').show();

    }

    return;
}

function selectAllCheckbox() {
    if($('#chkSelectAll').is(':checked')) {
        $('#contohdata-body tr').each(function() {
            $('.eq_check').prop('checked', true);
        });
    } else {
        $('#contohdata-body tr').each(function() {
            $('.eq_check').prop('checked', false);
        });
    }
}

function changeSelect() {
    $('#contohdata-body tr').each(function() {
        if(!$('.eq_check').is('checked')) {
            $('#chkSelectAll').prop('checked', false);
        }
    });
}

function getJobCentreAutoSearch(){
    var data = { "type": "C_SEARCH" } ;
    var url = "request.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onJobCentreAutoSearch,jobcentre_obj) ;
}

function onJobCentreAutoSearch(obj,resp) { 
    if (resp.status == C_OK) {
        if (resp.data != null || resp.data.length != 0 ) {
            var filteredBuilding = resp.data;

            $('#filterCustomerJobCentre').autocomplete({
                source: filteredBuilding,
                minLength: 1,
                autoFocus: true
            });
        }
    }
}

function populateCustDetail() {
  var custId = $("#cobCentreCustCode").val();
  var data = { "type": C_GET + "_CUSTDETAIL", "custId" : custId} ;
  var url = "request.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
  callServer(url,"json",data,onJobCentreResponse,jobcentre_obj) ;
}

function populateCustDetailverify() {
    var custId = $("#cobCentreCustCodeverif").val();

    $("#cobCentreCustCode").val(custId);

    var data = { "type": C_GET + "_CUSTDETAIL", "custId" : custId} ;
    var url = "request.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onJobCentreResponse,jobcentre_obj) ;
}

function populateLocationDetail() {
  var locId = $("#cobCentreLocCode").val();
  var data = { "type": C_GET + "_LOCDETAIL", "locId" : locId} ;
  var url = "request.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
  callServer(url,"json",data,onJobCentreResponse,jobcentre_obj) ;
}

function populateLocationDetailverify() {
    var locId = $("#cobCentreLocCodeverif").val();
    $("#cobCentreLocCode").val(locId);
    var data = { "type": C_GET + "_LOCDETAIL", "locId" : locId} ;
    var url = "request.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onJobCentreResponse,jobcentre_obj) ;
}

function populateModelbyBrandAndLoc() {
  var brandId = $("#txtCentreBrand").val();
  var locId = $("#cobCentreLocCode").val();
  var data = { "type": C_GET + "_MODEL", "brandId" : brandId, "locId" : locId} ;
  var url = "request.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
  callServer(url,"json",data,onJobCentreResponse,jobcentre_obj) ;
}

function populateSerialNumByBrandLocModel() {
  var brandId = $("#txtCentreBrand").val();
  var locId = $("#cobCentreLocCode").val();
  var modelId = $("#txtCentreModel").val();
  var data = { "type": C_GET + "_SERIALNUMB", "brandId" : brandId, "locId" : locId, "modelId" : modelId} ;
  var url = "request.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
  callServer(url,"json",data,onJobCentreResponse,jobcentre_obj) ;
}

function filterJobCentre(){
    var data = { 
            "type": C_JOB_CENTRE_FILTER, 
            "status": 'all',
            "sorts": sorts,
            "index": screen_index,
        };
    var url  = "index.pzx?c=" + jobcentre_url + "&t=" + C_JOB_CENTRE_FILTER  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onJobCentreResponse,null) ;
    return false;
}

function showEditJobCentre(id, obj) {
    jobcentre_obj = obj ;
    screen_index++;
    showProgress("loading Job Centre" ) ;
    var data  = { "type": C_UPDATE_JOB_CENTRE_VIEW, "id" : id , "sorts": sorts, "index": screen_index} ;
    var url   = "index.pzx?c=" + jobcentre_url + "&t=" + C_UPDATE_JOB_CENTRE_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onJobCentreResponse,null) ;
}

function popupDeleteJobCentre(id, obj){
    Swal.fire({
        title: "Delete Confirmation",
        text: "Confirm you want to delete the record?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes",
        confirmButtonColor: '#d33',
    }).then(function(result) {
        if (result.value) {
            var data = { 
                "type": C_DELETE_JOB_CENTRE,
                "id": id
            } ;
            var url = "index.pzx?c=" + jobcentre_url + "&t=" + C_DELETE_JOB_CENTRE  + "&d=" + new Date().getTime() ; 
            callServer(url,"json",data,onJobCentreResponse,obj) ;
        }
    });

    // swal("Are you sure you want to delete this Job Centre?", {
    //     buttons: {
    //         ok: true,
    //         cancel: "Cancel",
    //     },
    //   })
    //   .then((value) => {
    //     switch (value) {
    //       case "ok":
    //           var data = {"type": C_DELETE_JOB_CENTRE,"id": id} ;
    //           var url = "index.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
    //           callServer(url,"json",data,onJobCentreResponse,obj) ;
    //       break;
    //     }
    //   });
}

function updateJobCentre() {
    saveJobCentre(C_UPDATE) ;
}

function saveJobCentre(type){


    if (validateJobCentre()){
        var data = {        "type"              : type,
                            "id"                : $('#txtCentreId').val(),
                            "coyId"             : $('#cobCentreBU').val(),
                            "active"            : ($('#chkCentreActive').is(':checked') ? '1' : '0'),
                            "idcust"            : $('#cobCentreCustCode').val(), 
                            "idcontact"         : $('#txtCentrePMName').val(), 
                            "jobnumber"         : $('#txtCentreJobNumber').val(),
                            "jobname"           : $('#txtCentreJobName').val(),
                            "jobtype"           : $('#txtCentreJobType').val(),
                            "jobstartdate"      : $('#txtCentreJobStartDate').val(),
                            "jobenddate"        : $('#txtCentreJobEndDate').val(),
                            "totalmandays"      : $('#txtCentreTotalMandays').val(),
                            "billing"           : getJobCentreBilling(),
                            "job_task"          : getJobPlan(),   
                            "resources"         : getJobResources(),   
                            // "idloc"             : $('#cobCentreLocCode').val(), 
                            // "coyname"           : $('#txtCentreCoyName').val(),
                            // "jobconfirmdate"    : $('#txtCentreJobConfirmDate').val(),
                            // "producttype"       : $('#txtCentreProductType').val(),
                            // "grn_id"            : $('#txtCentreGrn').val(),
                            // "equipment"         : "",
                            // "list_equipment"     : "",

                        };
        var url  = "index.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onJobCentreResponse,jobcentre_obj) ;
    } 
}

function getJobCentreBilling(){
    var lines = "" ;
    var sep = "" ;

    for (var i = 1; i <= 4; i++) {
        lines = lines + sep + $('#txtCentreBillInt'+i).val()  + "~" + 
                $('#txtCentreBillAmt'+i).val() + "~" + $('#txtBillDate'+i).val() + "~" + $('#txtCentreBillMandays'+i).val() + "~" + 
                $('#txtCentreInvoiceNo'+i).val() + "~" + $('#txtCentrePaidMandays'+i).val();
        sep = "|" ;
    }
    // throw new Error(lines);
    return lines ;
}

function showJobCentreBilling(lines) {
    if (lines == undefined || lines == null || lines == "") return ;
    
    var line = lines.split('|') ;
    var fld = "" ;
    m_billing_idx = 0 ;
    for (var i = 0 ; i < line.length ; i++) {
        if (line[i] != "") {
            fld = line[i].split('~') ;
            m_billing_idx++;
            
            $('#txtCentreBillInt'+m_billing_idx).val(fld[0]);
            $('#txtCentreBillAmt'+m_billing_idx).val(fld[1]);
            $('#txtBillDate'+m_billing_idx).val(fld[2]);
            $('#txtCentreBillMandays'+m_billing_idx).val(fld[3]);
            $('#txtCentreInvoiceNo'+m_billing_idx).val(fld[4]);
            $('#txtCentrePaidMandays'+m_billing_idx).val(fld[5]);
        }
    }
}

function getJobResources(){
    // var data = {    
    //             'accManager'        : getJobAccManager(),   
    //             'ProjManager'       : getProjManager(),   
    //             'TechConsultant'    : getTechConsultant(),   
    //             'AppConsultant'     : getAppConsultant(),   
    //             'Developer'         : getDeveloper(),   
    //             'CustProjSponsor'   : getCustProjSponsor(),   
    //             'CustProjAdvisor'   : getCustProjAdvisor(),   
    //             'CustProjManager'   : getCustProjManager(),   
    //             'CustProjMember'    : getCustProjMember(),   
    //             };

    // console.log(data);
    // return JSON.stringify(data);

    //==
    var arrays = [];
    
    var acc_mgr_array = getJobAccManager();
    arrays.push(acc_mgr_array);

    var proj_mgr_array = getProjManager();
    arrays.push(proj_mgr_array);
    
    var tech_cons_array = getTechConsultant();
    arrays.push(tech_cons_array);

    var app_cons_array = getAppConsultant();
    arrays.push(app_cons_array);

    var dev_array = getDeveloper();
    arrays.push(dev_array);

    var cust_proj_sponsor_array = getCustProjSponsor();
    arrays.push(cust_proj_sponsor_array);

    var cust_proj_advisor_array = getCustProjAdvisor();
    arrays.push(cust_proj_advisor_array);

    var cust_proj_mgr_array = getCustProjManager();
    arrays.push(cust_proj_mgr_array);

    var cust_proj_member_array = getCustProjMember();
    arrays.push(cust_proj_member_array);

    console.log(arrays);
    return JSON.stringify(arrays) ;
}

function getJobAccManager() {
    var arrays = [];
    var data = {};
    $('#acc-mgr-table tr').each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        if($('#cmbAccMgr-'+idx).val() != 0) {
            data = { 
                "id"        : $('#txtIdAccMgr'+idx).val()  ,
                "type"      : C_ACCOUNT_MANAGER,
                "user"      : $('#cmbAccMgr-'+idx).val()  ,      
                };
            arrays.push(data);
        }
    });

    return arrays;
}

function getProjManager() {
    var arrays = [];
    var data = {};
    $('#proj-mgr-table tr').each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        // console.log(idx);
        if($('#cmbProjMgr-'+idx).val() != 0) {
            data = { 
                "id"        : $('#txtIdProjMgr'+idx).val()  ,
                "type"      : C_PROJECT_MANAGER,
                "user"      : $('#cmbProjMgr-'+idx).val()  ,      
                };
            arrays.push(data);
        }
    });
    
    return arrays;
}

function getTechConsultant() {
    var arrays = [];
    var data = {};
    $('#tech-consultant-table tr').each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        // console.log(idx);
        if($('#cmbTechConsultant-'+idx).val() != 0) {
            data = { 
                "id"        : $('#txtIdTechConsultant'+idx).val()  ,
                "type"      : C_TECHNICAL_CONSULTANT,
                "user"      : $('#cmbTechConsultant-'+idx).val()  ,      
                };
            arrays.push(data);
        }
    });

    return arrays;
}

function getAppConsultant() {
    var arrays = [];
    var data = {};
    $('#app-consultant-table tr').each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        if($('#cmbAppConsultant-'+idx).val() != 0) {
            data = { 
                "id"        : $('#txtIdAppCons'+idx).val()  ,
                "type"      : C_APPLICATION_CONSULTANT,
                "user"      : $('#cmbAppConsultant-'+idx).val()  ,      
                };
            arrays.push(data);
        }
    });

    return arrays;
}

function getDeveloper() {
    var arrays = [];
    var data = {};
    $('#developer-table tr').each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        if($('#cmbDeveloper-'+idx).val() != 0) {
            data = { 
                "id"        : $('#txtIdDeveloper'+idx).val()  ,
                "type"      : C_DEVELOPER,
                "user"      : $('#cmbDeveloper-'+idx).val()  ,      
                };
            arrays.push(data);
        }
    });
    
    return arrays;
}

function getCustProjSponsor() {
    var arrays = [];
    var data = {};
    $('#cust-proj-sponsor-table tr').each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        if($('#cmbCustProjSponsor-'+idx).val() != 0) {
            data = { 
                "id"        : $('#txtIdCustProjSponsor'+idx).val()  ,
                "type"      : C_CUST_PROJECT_SPONSOR,
                "user"      : $('#cmbCustProjSponsor-'+idx).val()  ,      
                };
            arrays.push(data);
        }
    });
    
    return arrays;
}

function getCustProjAdvisor() {
    var arrays = [];
    var data = {};
    $('#cust-proj-advisor-table tr').each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        if($('#cmbCustProjAdvisor-'+idx).val() != 0) {
            data = { 
                "id"        : $('#txtIdCustProjAdvisor'+idx).val()  ,
                "type"      : C_CUST_PROJECT_ADVISOR,
                "user"      : $('#cmbCustProjAdvisor-'+idx).val()  ,      
                };
            arrays.push(data);
        }
    });
    
    return arrays;
}

function getCustProjManager() {
    var arrays = [];
    var data = {};
    $('#cust-proj-mgr-table tr').each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        if($('#cmbCustProjMgr-'+idx).val() != 0) {
            data = { 
                "id"        : $('#txtIdcmbCustProjMgr'+idx).val()  ,
                "type"      : C_CUST_PROJECT_MANAGER,
                "user"      : $('#cmbCustProjMgr-'+idx).val()  ,      
                };
            arrays.push(data);
        }
    });
    
    return arrays;
}

function getCustProjMember() {
    var arrays = [];
    var data = {};
    $('#cust-proj-member-table tr').each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        if($('#cmbCustProjMember-'+idx).val() != 0) {
            data = { 
                "id"        : $('#txtIdCustProjMember'+idx).val()  ,
                "type"      : C_CUST_PROJECT_MEMBER,
                "user"      : $('#cmbCustProjMember-'+idx).val()  ,      
                };
            arrays.push(data);
        }
    });
    
    return arrays;
}



function showJobCentreServiceReport(lines) {
    if (lines == undefined || lines == null || lines == "") return ;
    
    var line = lines.split('|') ;
    var fld = "" ;
    m_service_report_idx = 0 ;

    for (var i = 0 ; i < line.length ; i++) {
        if (line[i] != "") {
            fld = line[i].split('~') ;
            m_service_report_idx++;
            
            $('#service-plan-table').append(
                '<tr id="trJobPlanService' + m_service_report_idx + '" class="dnd-moved kt-datatable__row">'+
                    '<td class="kt-datatable__cell" style="display:none;">' + 
                        fld[0]+
                    '</td>' +
        
                    '<td   class="kt-datatable__cell">'+
                        fld[1]+
                    '</td>'+
        
                    '<td  class="kt-datatable__cell">' + 
                        fld[2]+
                    '</td>' +
        
                    '<td lass="kt-datatable__cell">'+
                        fld[3]+
                    '</td>' +
        
                    '<td  class="kt-datatable__cell">'+
                        fld[4]+
                    '</td>' +
        
                    '<td  class="kt-datatable__cell">'+
                        fld[5]+
                    '</td>' +
        
                    '<td  class="kt-datatable__cell">' + 
                        '<p style="text-align:right;margin-bottom:0px;">'+fld[6]+'</p>'+
                    '</td>' +
        
                    '<td  class="kt-datatable__cell">'+
                        '<p id="lblServiceHours" style="text-align:right;margin-bottom:0px;">'+fld[6]+'</p>'+
                    '</td>' +
                    
                    '<td class=\"kt-datatable__cell\" style="width:40px;">'+
                        '<button title="Print Preview" id="btnPrintService" onclick="return showServicePlanPrintPreview('+fld[0]+');" class="btn btn-primary btn-sm btn-icon btn-icon-md ml-2"><i class="fa fa-print"></button>'+
                    '</td>'+
                '</tr>'
            ); 
        }
    }
}

function showServicePlanPrintPreview(id){
    var url = "index.pzx?c=" + jobcentre_url + "&id=" + id +
            "&t=" + C_SERVICE_PLAN_PRINT_PREVIEW + "&r=1";

    showReport(url) ;
}

function validateJobCentre(){
    if ($('#cobCentreCustCode').val()==0) {
        Swal.fire("Error", "Customer Code cannot be blank", "error");
        return false;
    }

    if ($('#txtCentreJobName').blank()) {
        Swal.fire("Error", "Job Title cannot be blank", "error");
        return false;
    }

    var result = 0;
    for(var i = 1; i <= 4; i++) {
        result += parseInt($('#txtCentreBillInt'+i).val()) || 0;
    }

    if (result>100 || result < 100) {
        Swal.fire("Error", "Total of Billing Interval must be 100%", "error");
        return false;
    }
    // $("#saveJobCentreConfirmationView").modal("hide");

    return true;
}

function showJobCentreUtilization(id){
    showProgress("loading Job Centre Print Preview" ) ;
    screen_index++;
    var data = { "type": C_SHOW_UTILIZATION,
                 "jobCentreId"  : id, 
                 "index": screen_index} ;
    var url  = "index.pzx?c=" + jobcentre_url + "&t=" + C_SHOW_UTILIZATION  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onJobCentreResponse,null) ;
}

function showPrintJobCentreUtilizationPreview(id){
    var lines = "";
    var separator = "";
    $('#utilizationBody tr.parent').each(function() {
        /**check whether th icon is up or down  */
        line_id           = $('.tdDetailId',this).html();
        colapse_condition = $('.tdCollapse',this).html();

        lines = lines +  separator + line_id + "~" + colapse_condition;

        separator = "|";

    });

    var url = "index.pzx?c=" + jobcentre_url + "&id=" + id + "&t=" + C_SHOW_UTILIZATION_REPORT+"&fn=" + lines  + "&r=1";
    showReport(url) ;
}

function showJobPlanPrintPreview (id){
    var url = "index.pzx?c=" + jobcentre_url + "&id=" + id + "&t=" + C_SHOW_JOB_PLAN_REPORT+"&r=1";
    showReport(url) ;
}

function onJobCentreResponse(obj,resp){
	// $('#activityLoadingModal').modal('hide');
    if (resp.status != C_OK ) {
        Swal.fire("Error", resp.mesg, "error");
        return false;
    }

    if(resp.type == C_JOB_CENTRE_FILTER || resp.type == C_SORT) {

        var wrapper = $('#jobcentre_row_filter');
        wrapper.nextAll().remove();
        wrapper.after(resp.data);
        filterData($('#txtcolstatusplan'),5);
    }
    else if (resp.type == C_UPDATE_JOB_CENTRE_VIEW) {
        showScreen(resp);
        showContentIndex(resp.data.all);

        var dteopt = {
            todayHighlight: true,
            orientation: "bottom left",
            autoclose: true,
            format: 'dd/mm/yyyy',
            templates: {
                leftArrow: '<i class="la la-angle-left"></i>',
                rightArrow: '<i class="la la-angle-right"></i>'
            }
        }

        $("#txtCentreJobStartDate").datepicker(dteopt) ;
        $("#txtCentreJobEndDate").datepicker(dteopt) ;
        $('#txtCentreId').val(resp.data.headerData.id) ;
        $('#cobCentreBU').val(resp.data.headerData.bu) ;
        $('#txtCentreJobNumber').val(resp.data.headerData.jobnumber) ;
        $('#txtCentreJobStartDate').val(resp.data.headerData.jobstartdate) ;
        $('#cobCentreCustCode').val(resp.data.headerData.cust) ;
        $('#txtCentreJobType').val(resp.data.headerData.jobtype) ;
        $('#txtCentreCoyName').val(resp.data.headerData.coyname) ;
        $('#txtCentreJobName').val(resp.data.headerData.jobname) ;
        
        $('#txtCentreJobEndDate').val(resp.data.headerData.jobenddate) ;
        $('#txtCentrePMName').html(resp.data.headerData.pmname_opt) ;
        $('#txtCentrePMName').val(resp.data.headerData.pmname) ;

        //resource
        $("#cmbCustProjSponsor").html(resp.data.headerData.pmname_opt) ;
        $("#cmbCustProjAdvisor").html(resp.data.headerData.pmname_opt) ;
        $("#cmbCustProjMgr").html(resp.data.headerData.pmname_opt) ;
        $("#cmbCustProjMember").html(resp.data.headerData.pmname_opt) ;
        //==

        $('#txtCentreTotalMandays').val(resp.data.headerData.totalmandays) ;
        $('#txtCentreTotalHours').val(parseFloat(resp.data.headerData.totalmandays*8)) ;

        showJobCentreBilling(resp.data.headerData.jobcentre_billing);
        showJobCentreServiceReport(resp.data.headerData.jobcentre_servicereport);
        
        

        var myResources = JSON.parse(resp.data.headerData.jobcentre_resources);
        showJobResources(myResources);

        if(resp.data.headerData.status == '1'){
            $('#chkCentreActive').prop('checked', true);
        } else {
            $('#chkCentreActive').prop('checked', false);
        }

        var myObj = JSON.parse(resp.data.headerData.jobcentre_task);
        showJobPlan(myObj,resp.data.headerData.status);

        getTotalPlanAllocated() ;
        getTotalPlanServiceAllocated() ;

        var functionName = "updateJobCentre()";
        
        var strBtn =  "<button type=\"button\" onclick=\"prevscreen();\" class=\"btn btn-secondary\">Cancel</button>" +
                        "<button id=\"btnMasterAdd\" class=\"btn btn-brand ml-3\" onclick=\"return "+functionName+";\">Save</button>";

        $('#btnJobCentre').html(strBtn); 

    } else if (resp.type == C_UPDATE) {
        Swal.fire("Success", resp.mesg, "success");
        filterJobCentre();
        prevscreen();
    } else if (resp.type == C_DELETE_JOB_CENTRE) {
        Swal.fire("Success", resp.mesg, "success");
        filterJobCentre();
    } else if (resp.type == C_GET + '_CUSTDETAIL') {

        $("#txtCentreCoyName").val(resp.data.coyName);
        $("#txtCentrePMName").html(resp.data.name);

        $("#cmbCustProjSponsor").html(resp.data.name);
        $("#cmbCustProjAdvisor").html(resp.data.name);
        $("#cmbCustProjMgr").html(resp.data.name);
        $("#cmbCustProjMember").html(resp.data.name);
      
    } else if (resp.type == C_GET + '_LOCDETAIL') {

        $("#txtCentreLocContactName").val(resp.data.contactname);
        $("#txtCentreLocContactPhone").val(resp.data.contactphone);
        $("#txtCentreLocContactEmail").val(resp.data.contactemail);
        $("#txtCentreLocContactAddress").val(resp.data.address);
        $("#txtCentreProductType").html(resp.data.productlist);
        $("#txtCentreBrand").html(resp.data.brandlist);
        $("#txtCentreModel").html(resp.data.modellist);
        $("#txtCentreSerialNumber").html(resp.data.serialnumblist);

        $("#txtCentreLocContactNameverif").val(resp.data.contactname);
        $("#txtCentreLocContactPhoneverif").val(resp.data.contactphone);
        $("#txtCentreLocContactEmailverif").val(resp.data.contactemail);
        $("#txtCentreLocContactAddressverif").val(resp.data.address);

        getLocationEquipment(resp.data.locationId);
      
    } else if (resp.type == C_GET + '_MODEL') {
      $("#txtCentreModel").html(resp.data.modellist);
    } else if (resp.type == C_GET + '_SERIALNUMB') {
      $("#txtCentreSerialNumber").html(resp.data.serialnumblist);
    } else if (resp.type == C_SHOW_UPLOAD_ATTACH_VIEW ) {
        hideProgress(); 

        $('#modaluploadDocJobCentreContent').html(resp.data.content);
        
        $('#uploadFile').on('change',function () {
            $('#uploadMsg').text("");
            $('#errorMsg').text("");
            
            upload_form = this.form;
            strHtml     = "";
            fileList    = this.files;

            for(var i = 0; i < fileList.length; i++) {
                img = fileList[i];
                imgName = img.name;
                
                strHtml +=  "<tr id='system_doc_"+img_idx+"'><td>"+
                                "Document Reference : &nbsp;&nbsp; <input style='margin-right:40px' size=17  type='text' name='txtDesc[]' value=''/>" +
                                "</td>" +
                                "<td>" + imgName +"</td>" +
                                "</tr>";
                img_idx ++;
            }
            $("#jobcentre_docs_upload").html(strHtml);
        });
        
        var strBtn = resp.data.button;
        $('#modaluploadDocJobCentreButtonContent').html(strBtn);

    } else if (resp.type == C_SHOW_UTILIZATION) {
        // $('#modalJobCentreReportUtilizationViewContent').html(resp.data.all);

        showScreen(resp);
        showContentIndex(resp.data.all);

        var strBtn = "<button id=\"btnJobCentreReportUtilizationPrint\" class=\"btn btn-success\" onclick=\"javascript:showPrintJobCentreUtilizationPreview("+resp.data.id+");\" title=\"Print\"><i class='fa fa-print'></i>Print</button>"+
                    "<button type=\"button\" class=\"btn btn-secondary ml-2\" onclick=\"prevscreen();\" data-dismiss=\"modal\">Close</button>";

        $('#btnJobUtilization').html(strBtn);

    }  else if (resp.type == C_SHOW_ASSIGNMENT_LIST_VIEW) {
        $("#showJobAssignmentView").modal("show");
        $('#modalShowJobAssignmentHeaderViewContent').html(resp.data.all);

        $('#cobAssignNumber').val(resp.data.headerData.jobnumber) ;
        $('#txtJobCentreId').val(resp.data.headerData.jobcentre) ;

        $('#txtAssignId').val(resp.data.headerData.id) ;
        $("#txtAssignJobName").val(resp.data.headerData.jobname);
        $('#txtAssignConfirmDate').val(resp.data.headerData.jobconfirmdate) ;
        $('#txtAssignStartDate').val(resp.data.headerData.jobstartdate) ;
        $('#cobAssignJobType').val(resp.data.headerData.jobtype) ;
        $('#cobAssignProductType').val(resp.data.headerData.producttype) ;
        $('#cobAssignBrand').val(resp.data.headerData.brand) ;
        $('#cobAssignModel').val(resp.data.headerData.model) ;
        $('#txtAssignSerialNumb').val(resp.data.headerData.serialnumber) ;
        $('#cobAssignEquiptment').html(resp.data.headerData.equipment) ;
        $('#txtAssignAgent').val(0) ;

        showJobAssignmentDetailList(resp.data.headerData.detail);

        var strBtn = "<button id=\"btnMasterAdd\" class=\"btn btn-danger\" onclick=\"javascript: popupDeleteJobAssignmentList('" + resp.data.headerData.id + "', this);\">Delete</button>"+
                        "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                        "<button  type=\"button\" class=\"btn btn-secondary\" onclick=\"return showAgentScheduleList();\">Agent Schedule</button>" +
                        "<button id=\"btnMasterAdd\" class=\"btn btn-primary\" onclick=\"return updateJobAssignment();\">Save</button>";

        $('#modalShowJobAssignmentHeaderViewButtonContent').show().html(strBtn); 
    } else if (resp.type == "C_JOB_DETAIL_VIEW") {
        $('#jobDetailView').modal('show');
        $('#jobDetailViewViewContent').html(resp.data.htmlContent);
        
        $('#txtCentreCoyName').val(resp.data.coyname);
        $('#cobCentreCustCode').val(resp.data.cust);
        $('#cobCentreLocCode').val(resp.data.loc);
        $('#txtCentreLocContactName').val(resp.data.contactname);
        $('#txtCentreLocContactPhone').val(resp.data.contactphone);
        $('#txtCentreLocContactEmail').val(resp.data.contactemail);
        $('#txtCentreLocContactAddress').val(resp.data.address);
        $('#txtCentreJobNumber').val(resp.data.jobnumber);
        $('#txtCentreJobType').val(resp.data.jobtype);
        $('#txtCentreJobName').val(resp.data.jobname);
        $('#txtCentreJobConfirmDate').val(resp.data.jobconfirmdate);
        $('#txtCentreJobStartDate').val(resp.data.jobstartdate);
        $('#txtCentreTotalMandays').val(resp.data.totalmandays);
        $('#planEquipmentData-body').html(resp.data.jobcentre_list_equipment);
    } else if(resp.type == 'C_AGENT_SCHEDULE_TABLE4'){
        $('#calendar').html('');
        init_calendar(
            resp.data.data,
            resp.data.start_time,
            resp.data.end_time,
            resp.data.date,
            resp.data.enddate
            );

           
        $('#agentSchedule4').modal('show');
        $('#agentSchedule4').show(function(){
            $('.fc-timeGridWeek-button').trigger('click');
        });
        
        
    }else if(resp.type == 'C_CONVERT_PLAN'){
        Swal.fire("Success", resp.mesg, "success");
    }else if(resp.type == "C_SAVE_JOBPLAN_TEMPLATE"){
        $('#JobPlanTemplateName').val("");
        $('#chkJobPlanTempOption').prop('checked', true);
        $('#JobPlanTemplateList').val(0);
        // $('#jobPlanTemplateNewName').val("");

        $('#SaveJobPlanTemplateConfirmationView').modal('hide'); 
        Swal.fire("Success", resp.mesg, "success");
      
    }else if(resp.type == "C_VIEW_LOAD_JOBPLAN_TEMPLATE"){
        var strBtn = "<button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">Cancel</button>" +
                     "<button onclick=\"DeleteTemplateJobPlan();\" type=\"button\" class=\"btn btn-danger ml-2\" >Delete</button>" +
                     "<button onclick=\"LoadTemplateJobPlan();\" class=\"btn btn-primary ml-2\" > Load </button>";

        $('#modalLoadJobPlanTemplateConfirmationButton').html(strBtn);
        $("#JobPlanTemplateLoad").html(resp.data.load_option);
      
    } else if(resp.type == "C_VIEW_LOAD_JOBPLAN_TEMPLATE_LIST"){
        $("#JobPlanTemplateList").html(resp.data.load_option);
    }
    else if(resp.type == "C_LOAD_JOBPLAN_TEMPLATE"){
        $('#LoadJobPlanTemplateConfirmationView').modal('hide'); 
         var myObj = JSON.parse(resp.data.jobcentre_task);
         showJobPlanTemplate(myObj);
    } else if(resp.type == "C_DELETE_JOBPLAN_TEMPLATE"){
         Swal.fire("Success", resp.mesg, "success");
    } else if(resp.type == "CHECK_TASK_BALLANCE"){
        Swal.fire({
            title: "Complete Task Confirmation",
            text: "Confirm you want to complete this task?  remaining balance : "+resp.data.balance,
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            confirmButtonColor: '#26C281',
        }).then(function(result) {
            if (result.value) {
                
                 var data = { 
                 "job_id"            : resp.data.job_id,
                 "task_id"           : resp.data.task_id,
                 "type"          : "C_COMPLETE_TASK"
                 };
                 var url = "index.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
                 callServer(url,"json",data,onJobCentreResponse,null) ;
            }
        });
    }else if(resp.type == "C_COMPLETE_TASK"){
        console.log(resp.data);
        $(".SpanJobStatus"+resp.data.task_id).html("Completed");
        $(".SpanJobStatus"+resp.data.task_id).css("background-color","#26C281") ;
      
        Swal.fire("Success", resp.mesg, "success");
    }
}

//===Job Assignment===


//==============DOCUMENT=============================
function downloadJobCentreFile(id, filename){
    var url = "index.pzx?c=" + jobcentre_url + "&id=" + id +
        "&fn=" + filename + "&t=" + C_DOWNLOAD_ATTACHMENT  + "&r=1";
    showReport(url) ;
}

function removeJobCentreFile(docId) {
    var data  = { "type"    : C_DELETE_ATTACHMENT,
                 "jobcentre_id" : $('#jobcentre_id').val(), 
                 "doc_id"   : docId};
    var url   = "index.pzx?c=" + jobcentre_url + "&t=" + C_DELETE_ATTACHMENT  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onJobCentreDocumentResponse,null) ;
}

function cancelJobCentreDocs() {
    $('#jobcentre_docs_upload').html("");
    return false;
}

function cancelDoc(){
   var data  = { "type"    : C_CANCEL_ATTACHMENT,
                 "jobcentre_id" : 0};
    var url   = "index.pzx?c=" + jobcentre_url + "&t=" + C_CANCEL_ATTACHMENT  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onJobCentreDocumentResponse,null) ;
}

//SHOW
function showJobCentreDocsView(id, obj) {
    showProgress("loading Upload Document View" ) ;
    
    var data  = { "type": C_SHOW_UPLOAD_ATTACH_VIEW, "id" : id} ;
    var url   = "index.pzx?c=" + jobcentre_url + "&t=" + C_SHOW_UPLOAD_ATTACH_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onJobCentreResponse,null) ;
}

function showJobCentreDocs() {
    if($('#jobcentre_docs_upload').text().trim() != "") {
        $("#btnJobCentreCancelUpload").prop('disabled',true);
        var url  = "index.pzx?c=" + jobcentre_url + "&t=" + C_SHOW_UPLOAD_ATTACH_DOC  + "&d=" + new Date().getTime() + "&jobcentre_id=" + $("#jobcentre_id").val() ;
        $('#jobcentre_docs_upload').show() ;
        ajaxUpload(upload_form,url,jobCentreShowUploadEnd);

    }
    return false;
}

function jobCentreShowUploadEnd(resp) {
    var msgArr      = resp.split("*");
    var status      = msgArr[0];
    var centreItems = msgArr[1];
    var error       = msgArr[2];
    
    if(status == "0") {
        $("#errorMsg").text("");
        $("#uploadMsg").text("");
    } else {
        
        $("#uploadMsg").text("");
        errorMsg = "Error uploading" + error;
        $("#errorMsg").text(errorMsg);
        return;
    }

    docItems    = centreItems.split("~");
    docItemHtml = "";
    for(var i = 0; i < docItems.length; i++) {
        docElements = docItems[i].split("|");
        docItemHtml += "<tr id='trdocs"+docElements[3]+"'>" +
                      "<td>"  + docElements[1] + " (" + docElements[0] + ")" + "</td>" +
                      "<td> <input name='txtDescs' type='text' value='"+docElements[2]+"' ></td>" +
                      "<td style='width:40px;text-align:center;'>"+
                        "<a class='fa fa-search' title='Preview' style='color:green; margin-top: 5px;' href='javascript:' onclick='downloadJobCentreFile(\"" + docElements[4] +  "\", \"" + docElements[1] + "\")'>"+
                        "</a>&nbsp;&nbsp;&nbsp;<a class='fa fa-trash' title='Remove' style='color:red; margin-top: 5px;' href='javascript:' onclick='removeJobCentreFile(" + docElements[3] + ")'></a>"+
                      "</td>" +
                      "<input type='hidden' name='lblIds' value='"+ docElements[3] +"'>" +
                      "</tr>";
    }
    
    $("#jobcentre_docs_list tr:first").after(docItemHtml);
    $('#fileNameItem').html("");
    document.getElementById("form-upload-jobcentre").reset();
}

function saveShowJobCentreDoc() {
    var docIds      = [];
    var descList    = []; 
    
    $('input[name="txtDescs"]').each(function () {
        descList.push(this.value);
    });
    
    $('input[name="lblIds"]').each(function () {
        docIds.push(this.value);
    });
    
    var data = { "type"     : C_SHOW_SAVE_ATTACHMENT,
                 "jobCentreId"  : $('#jobcentre_id').val(), 
                 "docIds"   : docIds, 
                 "descList" : descList };
    var url  = "index.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onJobCentreDocumentResponse,null) ;
}

function onJobCentreDocumentResponse(obj,resp) {
    if (resp.type == C_DELETE_ATTACHMENT) {
        $('#trdocs'+resp.data).remove() ;
    } else if (resp.type == C_SHOW_SAVE_ATTACHMENT) {
        $('#uploadMsg').text("All documents are updated successfully!!");
    }
}

//=================================================================

function showJobPlan(myObj, jobComplete){
    job_plan_idx = 2000;
    var id_max = [2000];
    for (i in myObj) {
      
        id = myObj[i].id;

        phase = myObj[i].phase;
        task = myObj[i].task;
        desc = myObj[i].desc;
        //scope = myObj[i].scope;
        date = myObj[i].date;
        hours = myObj[i].hours;
        time = myObj[i].date_end;

        consultant_id = myObj[i].agent;
        remarks = myObj[i].remarks;
        status = myObj[i].status;
        venue = myObj[i].venue;
        closed_user = myObj[i].closed_user;
        closed_date = myObj[i].closed_date;
        closed_message = myObj[i].closed_message;
        balance = myObj[i].balance;
        total_unaproved_report = myObj[i].total_unaproved_report;
        id_max.push(id);
        var consultant = '<select id="consultant-plan'+id+'" class="form-control txtConsultantPlan">'+$('#txtConsultantComb').html()+'</select>';
        var cmbJobPlanVenue = '<select id="cmbJobPlanVenue'+id+'" class="form-control cmbJobPlanVenue">'+$('#cmbJobPlanVenue').html()+'</select>';

        if(hours == 0) {
            val_hours = '';
        } else {
            val_hours = 'value="'+hours+'"';
        }

        $('#job-plan-table').append(
            '<tr id="trJobPlan' + id + '" class="dnd-moved kt-datatable__row">'+
                '<td class="kt-datatable__cell" style="display:none;">' + 
                    '<input  class="form-control txtIdPlan" id="txtIdPlan'+id+'" value="'+id+'">' + 
                '</td>' +
                '<td class="kt-datatable__cell" style="display:none;">' + 
                    '<input  class="form-control txtClosedUserPlan" id="txtClosedUserPlan'+job_plan_idx+'" value="'+closed_user+'">' + 
                '</td>' +

                '<td class="kt-datatable__cell" style="display:none;">' + 
                    '<input  class="form-control txtClosedDatePlan" id="txtClosedDatePlan'+job_plan_idx+'" value="'+closed_date+'">' + 
                '</td>' +
                '<td  class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<input type="text" class="form-control txtPhasePlan" id="phase-plan'+id+'" value="'+phase+'">'+
                '</td>'+
    
                '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                    '<input type="text" class="form-control txtTaskPlan" id="task-plan'+id+'" value="'+task+'">' + 
                    
                '</td>' +

                '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                    '<textarea class="form-control txtDescPlan" id="desc-task'+id+'" rows="2">'+desc+'</textarea>'+
                '</td>' +
    
                '<td class="kt-datatable__cell" style="display:none;vertical-align:top;">' + 
                    //'<input type="text" class="form-control txtRemarkPlan" id="remark-plan'+id+'" value="'+remarks+'">' + 
                    '<textarea class="form-control txtRemarkPlan" rows="3" maxlength="250" id="remark-plan'+id+'">'+remarks+'</textarea>'+
                '</td>' +
    
                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<div class="input-group date">'+
                        '<input type="text" class="form-control txtStartDatePlan" placeholder="Select date" id="startdate-plan' + id + '" onchange="setPlanDate(' + id + ');" maxlength="10" value="'+date+'"/>'+
                        '<div class="input-group-append">'+
                            '<span class="input-group-text">'+
                                '<i class="la la-calendar-check-o"></i>'+
                            '</span>'+
                        '</div>'+
                    '</div>'+
                '</td>' +
    
                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<div class="input-group date">'+
                        '<input type="text" class="form-control txtEndDatePlan" placeholder="Select date" id="enddate-plan' + id + '" onchange="setPlanDate(' + id + ');" maxlength="10" value="'+time+'"/>'+
                        '<div class="input-group-append">'+
                            '<span class="input-group-text">'+
                                '<i class="la la-calendar-check-o"></i>'+
                            '</span>'+
                        '</div>'+
                    '</div>'+
                '</td>' +
    
                '<td class="kt-datatable__cell" id="txtConsultant-' + id + '" style="vertical-align:top;">'+
                    consultant+
                '</td>' +
    
                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<input onchange="getTotalPlanAllocated()" id="hours-plan' + id + '"  type="number" class="col-lg-12 form-control text-right txtHoursPlan" '+val_hours+'>'+
                '</td>' +

                '<td class="kt-datatable__cell" id="cmbJobPlanVenue-' + id + '" style="vertical-align:top;">'+
                cmbJobPlanVenue +
                '</td>' +
                
                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<label title="'+closed_message+'" class="control-label SpanJobStatus'+id+'" style="background-color:'+(status == 1 ? '#26C281' :'#ff9800' )+'">'+(status == 1 ? 'Completed' :'Incomplete' )+'</label><br>'+
                    '<input style="display:none;" id="status-plan' + id + '" maxlength="10" type="text" class="form-control txtStatusPlan" value="'+status+'" >'+
                '</td>'+

                '<td class="kt-datatable__cell" style="vertical-align:top;text-align:center">'+
                    '<span style="text-align:right">'+balance+' d'+ '</span>'+
                '</td>'+
                
                '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-right:2px;">'+
                    '<button title="Line Remarks" id="btn-remark-'+id+'" onclick="lineRemarksJobPlan('+id+','+status+');" id="btnRemarks" class="btn btn-warning btn-sm btn-icon btn-icon-md"><i class="fa fa-comments" aria-hidden="true"></i></button>'+
                '</td>'+

                '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:2px;padding-right:2px;">'+
                    '<button title="Copy" id="btn-copy-'+id+'" onclick="javascript: copyJobPlan('+id+', this);" id="btnCopy" class="btn btn-info btn-sm btn-icon btn-icon-md btnCopy"><i class="fa fa-copy"></i></button>'+
                '</td>'+

                '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:2px;padding-right:2px;">'+
                    '<button title="Delete" id="btn-delete-'+id+'" onclick="javascript: deleteJobPlan('+id+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md btnDelete"><i class="fa fa-trash"></button>'+
                '</td>'+
                '<td class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:2px;padding-right:2px;">'+
                    '<button title="Complete Task" id="btnCompleteJobCentreTask'+id+'" onclick="showCompleteJobCentreModal('+id+', this)" class="btn btn-success btn-sm btn-icon btn-icon-md btnCompleteJobCentreTask" '+(status == 1 ? 'disabled' :'' )+'><i class="flaticon2-check-mark"></i></button>'+
                '</td>'+
            '</tr>'

         ); 
        
        if(status == 1){
            $('#job-plan-table #trJobPlan'+id).find('input, textarea, button, select').attr('disabled', true);
            $('#job-plan-table #trJobPlan'+id).find('#btn-remark-'+id).attr('disabled', false);
        }

        if(jobComplete==1) {
            $('#btnAddItem').attr('disabled', true);
            $('#btnSaveTemp').attr('disabled', true);
            $('#btnLoadTemp').attr('disabled', true);
            $('#txtAllocatedHours').attr('disabled', true);
            $('#job-plan-table #trJobPlan'+id).find('input, textarea, select').attr('disabled', true);
            $('#job-plan-table #trJobPlan'+id).find('.btnCopy').attr('disabled', true);
            $('#job-plan-table #trJobPlan'+id).find('.btnDelete').attr('disabled', true);
            $('#job-plan-table #trJobPlan'+id).find('.btnRemarks').attr('disabled', false);
        } 

        $("#consultant-plan"+id).val(consultant_id);
        $('#cmbJobPlanVenue'+id).val(venue);

        // var dteopt = {
        //     todayHighlight: true,
        //     orientation: "bottom left",
        //     autoclose: true,
        //     format: 'dd/mm/yyyy',
        //     templates: {
        //         leftArrow: '<i class="la la-angle-left"></i>',
        //         rightArrow: '<i class="la la-angle-right"></i>'
        //     }
        // }
        // $(".txtStartDatePlan").datepicker(dteopt) ;
        // $(".txtEndDatePlan").datepicker(dteopt) ;

        $('.txtStartDatePlan').datepicker({
            format: "dd/mm/yyyy",
            useCurrent : true,
            todayHighlight: true
        }); 

        $('.txtEndDatePlan').datepicker({
            format: "dd/mm/yyyy",
            useCurrent : true,
            todayHighlight: false,
            onSelect: function() {
                minDate : $('#startdate-plan' + id).val()
            }
        });
    
        $('#enddate-plan' + id).datepicker().datepicker('setDate', $('#enddate-plan' + id).val() );
   

        job_plan_idx = parseInt(id) +1;
    }

    job_plan_idx = Math.max.apply(null, id_max);

}


function showJobPlanTemplate(myObj){
    job_plan_idx = 2000;
    var id_max = [2000];
    var date = $('#txtCentreJobStartDate').val();
    $('#job-plan-table').html("");
    
    for (i in myObj) {
        
        id = myObj[i].id;

        phase = myObj[i].phase;
        task = myObj[i].task;
        desc = myObj[i].desc;
        
        hours = myObj[i].hours;

        consultant_id = myObj[i].agent;
        remarks = myObj[i].remarks;
        status = myObj[i].status;
        venue = myObj[i].venue;

        id_max.push(id);
        var consultant = '<select id="consultant-plan'+id+'" class="form-control txtConsultantPlan">'+$('#txtConsultantComb').html()+'</select>';
        var cmbJobPlanVenue = '<select id="cmbJobPlanVenue'+id+'" class="form-control cmbJobPlanVenue">'+$('#cmbJobPlanVenue').html()+'</select>';

        if(hours == 0) {
            val_hours = '';
        } else {
            val_hours = 'value="'+hours+'"';
        }

        $('#job-plan-table').append(
            '<tr id="trJobPlan' + id + '" class="dnd-moved kt-datatable__row">'+
                '<td class="kt-datatable__cell" style="display:none;">' + 
                    '<input  class="form-control txtIdPlan" id="txtIdPlan'+id+'" value="-1">' + 
                '</td>' +

                '<td class="kt-datatable__cell" style="display:none;">' + 
                    '<input  class="form-control txtClosedUserPlan" id="txtClosedUserPlan'+job_plan_idx+'" value="0">' + 
                '</td>' +

                '<td class="kt-datatable__cell" style="display:none;">' + 
                    '<input  class="form-control txtClosedDatePlan" id="txtClosedDatePlan'+job_plan_idx+'" value="">' + 
                '</td>' +
                '<td  class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<input type="text" class="form-control txtPhasePlan" id="phase-plan'+id+'" value="'+phase+'">'+
                '</td>'+
    
                '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                    '<input type="text" class="form-control txtTaskPlan" id="task-plan'+id+'" value="'+task+'">' + 
                '</td>' +

                '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                    '<textarea class="form-control txtDescPlan" id="desc-task'+id+'" rows="2">'+desc+'</textarea>'+
                '</td>' +
    
                '<td width="15.5%" class="kt-datatable__cell" style="display:none;vertical-align:top;">' + 
                    //'<input type="text" class="form-control txtRemarkPlan" id="remark-plan'+id+'" value="'+remarks+'">' + 
                    '<textarea class="form-control txtRemarkPlan" rows="3" maxlength="250" id="remark-plan'+id+'">'+remarks+'</textarea>'+
                '</td>' +
    
                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<div class="input-group date">'+
                        '<input type="text" class="form-control txtStartDatePlan" placeholder="Select date" id="startdate-plan' + id + '" onchange="setPlanDate(' + id + ');" value="'+date+'" maxlength="10"/>'+
                        '<div class="input-group-append">'+
                            '<span class="input-group-text">'+
                                '<i class="la la-calendar-check-o"></i>'+
                            '</span>'+
                        '</div>'+
                    '</div>'+
                '</td>' +
    
                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<div class="input-group date">'+
                        '<input type="text" class="form-control txtEndDatePlan" placeholder="Select date" id="enddate-plan' + id + '" onchange="setPlanDate(' + id + ');" value="'+date+'" maxlength="10"/>'+
                        '<div class="input-group-append">'+
                            '<span class="input-group-text">'+
                                '<i class="la la-calendar-check-o"></i>'+
                            '</span>'+
                        '</div>'+
                    '</div>'+
                '</td>' +
    
                '<td class="kt-datatable__cell" id="txtConsultant-' + id + '" style="vertical-align:top;">'+
                    consultant+
                '</td>' +
    
                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<input onchange="getTotalPlanAllocated()" id="hours-plan' + id + '" min="0" type="number" class="form-control text-right txtHoursPlan" '+val_hours+'>'+
                '</td>' +

                '<td class="kt-datatable__cell" id="cmbJobPlanVenue-' + id + '" style="vertical-align:top;">'+
                cmbJobPlanVenue +
                '</td>' +
    
                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<label class="control-label SpanJobStatus'+id+'" style="background-color:#ff9800">Incomplete</label><br>'+
                    '<input style="display:none;" id="status-plan' + id + '" maxlength="10" type="text" class="form-control txtStatusPlan" value="0" >'+
                '</td>'+
                '<td class="kt-datatable__cell" style="vertical-align:top;text-align:center">'+
                    '<span style="text-align:right">'+'0.00'+' d'+ '</span>'+
                '</td>'+
                '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;padding-right:0;">'+
                    '<button title="Line Remarks" onclick="lineRemarksJobPlan('+id+',0);" id="btnRemarks" class="btn btn-warning btn-sm btn-icon btn-icon-md"><i class="fa fa-comments" aria-hidden="true"></i></button>'+
                '</td>'+

                '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;padding-right:0;">'+
                    '<button title="Copy" onclick="javascript: copyJobPlan('+id+', this);" id="btnCopy" class="btn btn-info btn-sm btn-icon btn-icon-md"><i class="fa fa-copy"></i></button>'+
                '</td>'+

                '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;;padding-right:0;">'+
                    '<button title="Delete" onclick="javascript: deleteJobPlan('+id+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
                '</td>'+
                '<td class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;;padding-right:0;">'+
                    '<button title="Complete Task" id="btnCompleteJobCentreTask'+job_plan_idx+'" onclick="showCompleteJobCentreModal('+job_plan_idx+', this)" class="btn btn-success btn-sm btn-icon btn-icon-md btnCompleteJobCentreTask" disabled><i class="flaticon2-check-mark"></i></button>'+
                '</td>'+
            '</tr>'
         ); 
         
        $("#consultant-plan"+id).val(consultant_id);
        $('#cmbJobPlanVenue'+id).val(venue);

        // var dteopt = {
        //     todayHighlight: true,
        //     orientation: "bottom left",
        //     autoclose: true,
        //     format: 'dd/mm/yyyy',
        //     templates: {
        //         leftArrow: '<i class="la la-angle-left"></i>',
        //         rightArrow: '<i class="la la-angle-right"></i>'
        //     }
        // }

        // $(".txtStartDatePlan").datepicker(dteopt) ;
        // $(".txtEndDatePlan").datepicker(dteopt) ;

        $('.txtStartDatePlan').datepicker({
            format: "dd/mm/yyyy",
            useCurrent : true,
            todayHighlight: true
        }); 
        
        $('.txtEndDatePlan').datepicker({
            format: "dd/mm/yyyy",
            useCurrent : true,
            todayHighlight: false,
            onSelect: function() {
                minDate : $('#startdate-plan' + id).val()
            }
        });

        job_plan_idx = parseInt(id) +1;
    }

    job_plan_idx = Math.max.apply(null, id_max);

    getTotalPlanAllocated();

}

function addJobPlan() {
    job_plan_idx++;

    var date = $('#txtCentreJobStartDate').val();
    
    var consultant = '<select id="consultant-plan'+job_plan_idx+'" class="col-lg-12 form-control txtConsultantPlan">'+$('#txtConsultantComb').html()+'</select>';
    var cmbJobPlanVenue = '<select id="cmbJobPlanVenue'+job_plan_idx+'" class="form-control cmbJobPlanVenue">'+$('#cmbJobPlanVenue').html()+'</select>';

    $('#job-plan-table').append(
        '<tr id="trJobPlan' + job_plan_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtIdPlan" id="txtIdPlan'+job_plan_idx+'" value="-1">' + 
            '</td>' +

            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtClosedUserPlan" id="txtClosedUserPlan'+job_plan_idx+'" value="0">' + 
            '</td>' +

            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtClosedDatePlan" id="txtClosedDatePlan'+job_plan_idx+'" value="">' + 
            '</td>' +

            '<td  class="kt-datatable__cell" style="vertical-align:top;">'+
                '<input type="text" class="form-control txtPhasePlan" id="phase-plan'+job_plan_idx+'">'+
            '</td>'+

            '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                '<input type="text" class="form-control txtTaskPlan" id="task-plan'+job_plan_idx+'">' + 
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                '<textarea class="form-control txtDescPlan" id="desc-task'+job_plan_idx+'" rows="2"></textarea>'+
            '</td>' +

            '<td width="15.5%" class="kt-datatable__cell" style="display:none;vertical-align:top;">' + 
                //'<input type="text" class="form-control txtRemarkPlan" id="remark-plan'+job_plan_idx+'">' + 
                '<textarea class="form-control txtRemarkPlan" rows="3" maxlength="250" id="remark-plan'+job_plan_idx+'"></textarea>'+
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<div class="input-group date">'+
                    '<input type="text" class="form-control txtStartDatePlan" placeholder="Select date" id="startdate-plan' + job_plan_idx + '" value="'+date+'" onchange="setPlanDate(' + job_plan_idx + ');" maxlength="10"/>'+
                    '<div class="input-group-append">'+
                        '<span class="input-group-text">'+
                            '<i class="la la-calendar-check-o"></i>'+
                        '</span>'+
                    '</div>'+
                '</div>'+
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<div class="input-group date">'+
                    '<input type="text" class="form-control txtEndDatePlan" placeholder="Select date" id="enddate-plan' + job_plan_idx + '" value="'+date+'" onchange="setPlanDate(' + job_plan_idx + ');" maxlength="10"/>'+
                    '<div class="input-group-append">'+
                        '<span class="input-group-text">'+
                            '<i class="la la-calendar-check-o"></i>'+
                        '</span>'+
                    '</div>'+
                '</div>'+
            '</td>' +

            '<td class="kt-datatable__cell" id="txtConsultant-' + job_plan_idx + '" style="vertical-align:top;">'+
                consultant+
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<input onchange="getTotalPlanAllocated()" id="hours-plan' + job_plan_idx + '" min="0" type="number" class="form-control text-right txtHoursPlan">'+
            '</td>' +

            '<td class="kt-datatable__cell" id="cmbJobPlanVenue-' + job_plan_idx + '" style="vertical-align:top;">'+
            cmbJobPlanVenue +
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<label class="control-label SpanJobStatus'+job_plan_idx+'" style="background-color:#ff9800">Incomplete</label><br>'+
                '<input style="display:none;" id="status-plan' + job_plan_idx + '" maxlength="10" type="text" class="form-control txtStatusPlan" value="0" >'+
            '</td>'+

            '<td class="kt-datatable__cell" style="vertical-align:top;text-align:center">'+
                '<span style="text-align:right">'+'0.00'+' d'+ '</span>'+
            '</td>'+

            '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;padding-right:0;">'+
                '<button title="Line Remarks" onclick="lineRemarksJobPlan('+job_plan_idx+',0);" id="btnRemarks" class="btn btn-warning btn-sm btn-icon btn-icon-md"><i class="fa fa-comments" aria-hidden="true"></i></button>'+
            '</td>'+

            '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;padding-right:0;">'+
                '<button title="Copy" onclick="javascript: copyJobPlan('+job_plan_idx+', this);" id="btnCopy" class="btn btn-info btn-sm btn-icon btn-icon-md"><i class="fa fa-copy"></i></button>'+
            '</td>'+

            '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;padding-right:0;">'+
                '<button title="Delete" onclick="javascript: deleteJobPlan('+job_plan_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
            '</td>'+
            '<td class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;padding-right:0;">'+
                '<button title="Complete Task" id="btnCompleteJobCentreTask'+job_plan_idx+'" onclick="showCompleteJobCentreModal('+job_plan_idx+', this)" class="btn btn-success btn-sm btn-icon btn-icon-md btnCompleteJobCentreTask" disabled><i class="flaticon2-check-mark"></i></button>'+
            '</td>'+
        '</tr>'
    ); 

    // var dteopt = {
    //     todayHighlight: true,
    //     orientation: "bottom left",
    //     autoclose: true,
    //     format: 'dd/mm/yyyy',
    //     templates: {
    //         leftArrow: '<i class="la la-angle-left"></i>',
    //         rightArrow: '<i class="la la-angle-right"></i>'
    //     }
    // }

    // $(".txtStartDatePlan").datepicker(dteopt) ;
    // $(".txtEndDatePlan").datepicker(dteopt) ;

    $('.txtStartDatePlan').datepicker({
        format: "dd/mm/yyyy",
        useCurrent : true,
        todayHighlight: true
    }); 

    $('.txtEndDatePlan').datepicker({
        format: "dd/mm/yyyy",
        useCurrent : true,
        todayHighlight: false,
        onSelect: function() {
            minDate : $('#startdate-plan' + id).val()
        }
    });
    
    $('#enddate-plan' + id).datepicker().datepicker('setDate', $('#enddate-plan' + id).val() );
}

function deleteJobPlan(idx) {
    $('#trJobPlan'+idx).remove() ;
    getTotalPlanAllocated();
}

function copyJobPlan(idx) {
    $('#trJobPlan'+idx).each(function() { 
        phase       = $('.txtPhasePlan',this).val()  ;
        task        = $('.txtTaskPlan',this).val()  ;
        desc        = $('.txtDescPlan',this).val()  ;
        start_date  = $('.txtStartDatePlan',this).val()  ;
        end_date    = $('.txtEndDatePlan',this).val()  ;
        hours       = $('.txtHoursPlan',this).val()  ;
        consultant  = $('.txtConsultantPlan',this).val()  ;    
        remark      = $('.txtRemarkPlan',this).val()  ;      
        venue      = $('.cmbJobPlanVenue',this).val()  ;
    }); 

    job_plan_idx++;

    var consultantComb = '<select id="consultant-plan'+job_plan_idx+'" class="form-control txtConsultantPlan">'+$('#txtConsultantComb').html()+'</select>';
    var cmbJobPlanVenue = '<select id="cmbJobPlanVenue'+job_plan_idx+'" class="form-control cmbJobPlanVenue">'+$('#cmbJobPlanVenue').html()+'</select>';

    $('#job-plan-table').append(
        '<tr id="trJobPlan' + job_plan_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtIdPlan" id="txtIdPlan'+job_plan_idx+'" value="-1">' + 
            '</td>' +

            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtClosedUserPlan" id="txtClosedUserPlan'+job_plan_idx+'" value="0">' + 
            '</td>' +

            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtClosedDatePlan" id="txtClosedDatePlan'+job_plan_idx+'" value="">' + 
            '</td>' +
            
            '<td  class="kt-datatable__cell" style="vertical-align:top;">'+
                '<input type="text" class="form-control txtPhasePlan" id="phase-plan'+job_plan_idx+'" value="'+phase+'">'+
            '</td>'+

            '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                '<input type="text" class="form-control txtTaskPlan" id="task-plan'+job_plan_idx+'" value="'+task+'">' + 
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                '<textarea class="form-control txtDescPlan" id="desc-task'+job_plan_idx+'" rows="2">'+desc+'</textarea>'+
            '</td>' +

            '<td width="15.5%" class="kt-datatable__cell" style="display:none;vertical-align:top;">' + 
                //'<input type="text" class="form-control txtRemarkPlan" id="remark-plan'+job_plan_idx+'" value="'+remark+'">' + 
                '<textarea class="form-control txtRemarkPlan" rows="3" maxlength="250" id="remark-plan'+job_plan_idx+'">'+remarks+'</textarea>'+
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<div class="input-group date">'+
                    '<input type="text" class="form-control txtStartDatePlan" placeholder="Select date" id="startdate-plan' + job_plan_idx + '" onchange="setPlanDate(' + job_plan_idx + ');" value="'+start_date+'" maxlength="10"/>'+
                    '<div class="input-group-append">'+
                        '<span class="input-group-text">'+
                            '<i class="la la-calendar-check-o"></i>'+
                        '</span>'+
                    '</div>'+
                '</div>'+
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<div class="input-group date">'+
                    '<input type="text" class="form-control txtEndDatePlan" placeholder="Select date" id="enddate-plan' + job_plan_idx + '" onchange="setPlanDate(' + job_plan_idx + ');" value="'+end_date+'" maxlength="10"/>'+
                    '<div class="input-group-append">'+
                        '<span class="input-group-text">'+
                            '<i class="la la-calendar-check-o"></i>'+
                        '</span>'+
                    '</div>'+
                '</div>'+
            '</td>' +

            '<td class="kt-datatable__cell" id="txtConsultant-' + job_plan_idx + '" style="vertical-align:top;">'+
                consultantComb+
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<input onchange="getTotalPlanAllocated()" id="hours-plan' + job_plan_idx + '" min="0" type="number" class="form-control text-right txtHoursPlan" value="'+hours+'">'+
            '</td>' +

            '<td class="kt-datatable__cell" id="cmbJobPlanVenue-' + job_plan_idx + '" style="vertical-align:top;">'+
            cmbJobPlanVenue +
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<label class="control-label text-dark SpanJobStatus'+job_plan_idx+'" style="background-color:#ff9800">Incomplete</label><br>'+
                '<input style="display:none;" id="status-plan' + job_plan_idx + '" maxlength="10" type="text" class="form-control txtStatusPlan" value="0" >'+
            '</td>'+
            '<td class="kt-datatable__cell" style="vertical-align:top;text-align:center">'+
                '<span style="text-align:right">'+'0.00'+' d'+ '</span>'+
            '</td>'+
            '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;padding-right:0;">'+
                '<button title="Line Remarks" onclick="lineRemarksJobPlan('+job_plan_idx+',0);" id="btnRemarks" class="btn btn-warning btn-sm btn-icon btn-icon-md"><i class="fa fa-comments" aria-hidden="true"></i></button>'+
            '</td>'+

            '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;padding-right:0;">'+
                '<button title="Copy" onclick="javascript: copyJobPlan('+job_plan_idx+', this);" id="btnCopy" class="btn btn-info btn-sm btn-icon btn-icon-md"><i class="fa fa-copy"></i></button>'+
            '</td>'+

            '<td  class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;padding-right:0;">'+
                '<button title="Delete" onclick="javascript: deleteJobPlan('+job_plan_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
            '</td>'+
            '<td class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;padding-right:0;">'+
                '<button title="Complete Task" id="btnCompleteJobCentreTask'+job_plan_idx+'" onclick="showCompleteJobCentreModal('+job_plan_idx+', this)" class="btn btn-success btn-sm btn-icon btn-icon-md btnCompleteJobCentreTask" disabled><i class="flaticon2-check-mark"></i></button>'+
            '</td>'+
        '</tr>'
    );

    // var dteopt = {
    //     todayHighlight: true,
    //     orientation: "bottom left",
    //     autoclose: true,
    //     format: 'dd/mm/yyyy',
    //     templates: {
    //         leftArrow: '<i class="la la-angle-left"></i>',
    //         rightArrow: '<i class="la la-angle-right"></i>'
    //     }
    // }

    // $(".txtStartDatePlan").datepicker(dteopt) ;
    // $(".txtEndDatePlan").datepicker(dteopt) ;

    $('.txtStartDatePlan').datepicker({
        format: "dd/mm/yyyy",
        useCurrent : true,
        todayHighlight: true
    }); 

    $('.txtEndDatePlan').datepicker({
        format: "dd/mm/yyyy",
        useCurrent : true,
        todayHighlight: false,
        onSelect: function() {
            minDate : $('#startdate-plan' + id).val()
        }
    });
    
    $('#enddate-plan' + id).datepicker().datepicker('setDate', $('#enddate-plan' + id).val() );

    getTotalPlanAllocated();

}

function lineRemarksJobPlan(idx,status) {
    $("#lineRemakrsJobPlanView").modal("show");

    $("#modalLineRemakrsJobPlanContent").html('<textarea class="form-control" rows="3" maxlength="250" id="txtLineRemarksPlan'+idx+'"></textarea>');

    if($('#remark-plan'+idx).val() !="") {
        $("#txtLineRemarksPlan"+idx).val($('#remark-plan'+idx).val()); 
    }

    var strBtn = "";
    if(status==0) {
        strBtn = "<button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">Cancel</button>" +
                        "<button id=\"btnSaveLC\" class=\"btn btn-primary ml-2\" onclick=\"saveLineRemarks("+idx+");\">Save</button>" ;

        $('#modalLineRemakrsJobPlanButton').html(strBtn); 
    } else {
        $('#modalLineRemakrsJobPlanButton').html(strBtn); 
    }
    
}

function saveLineRemarks(idx) {
    $("#lineRemakrsJobPlanView").modal("hide");

    remarks = $("#txtLineRemarksPlan"+idx).val();
    $("#remark-plan"+idx).val(remarks);
}

function setPlanDate(idx) {
    //Calculate Day
    var startDate = moment($('#startdate-plan'+idx).val(), "DD/MM/YYYY");
    var endDate   = moment($('#enddate-plan'+idx).val(), "DD/MM/YYYY");
    Days          = endDate.diff(startDate, 'days');

    if (Days+1<=0) {
        Swal.fire('Error', "Date not valid, End Date must more than Start Date.", "error");

        $('#enddate-plan' + idx).val($('#startdate-plan' + idx).val());
        $('#enddate-plan' + idx).datepicker({
            format: "dd/mm/yyyy",
            useCurrent : true,
            todayHighlight: false,
            minDate : $('#startdate-plan' + idx).val()
        });

        $('#enddate-plan' + idx).datepicker().datepicker('setDate', $('#enddate-plan' + idx).val() );

        return false;
    }
}

function getJobPlan(){
    var arrays = [];
    $('#job-plan-table tr').each(function() { 

        var data = {     
                    "id"            :$('.txtIdPlan',this).val()  ,
                    "phase"         :$('.txtPhasePlan',this).val()  ,
                    "task"          :$('.txtTaskPlan',this).val()  ,
                    "desc"          :$('.txtDescPlan',this).val()  ,
                    "start_date"    :$('.txtStartDatePlan',this).val()  ,
                    "end_date"      :$('.txtEndDatePlan',this).val()  ,
                    "hours"         :$('.txtHoursPlan',this).val()  ,
                    "consultant"    :$('.txtConsultantPlan',this).val()  ,  
                    "remarks"       :$('.txtRemarkPlan',this).val()  ,  
                    "status"        :$('.txtStatusPlan',this).val()  ,  
                    "venue"         :$('.cmbJobPlanVenue',this).val()  ,
                    "closed_user"   :$('.txtClosedUserPlan',this).val()  , 
                    "closed_date"   :$('.txtClosedDatePlan',this).val()  ,  
                   };   

        arrays.push(data);
    }); 

    return JSON.stringify(arrays) ;
}

//==============================================

function getTotalPlanAllocated() {
    var total_hours = 0;
    var total_mandays = 0;

    $('#job-plan-table tr').each(function() {
        var hours = $('.txtHoursPlan',this).val()  ; 
        if(hours == "") {
            hours = 0;
        }     

        var mandays = parseFloat(hours);

        total_hours += mandays;

    }); 

    total_mandays = parseFloat(total_hours/8);
    $('#txtAllocatedHours').val(total_hours);
    $('#txtTotalPlanMandays').val(total_mandays);
}

function getTotalPlanServiceAllocated() {
    var total_hours = 0;

    $('#service-plan-table tr').each(function() {
        var hours       = parseFloat($('#lblServiceHours',this).text())  ; 
        total_hours += hours;
    }); 

    $('#txtTotalServiceHours').val(total_hours);
}

function getTimeTrackerDaysUpdatePlan(start,end){

    //Calculate Day

    var startDate = moment(start, "DD/MM/YYYY");
    var endDate = moment(end, "DD/MM/YYYY");
    var Days = endDate.diff(startDate, 'days');
        
    return Days;
}

function popupSaveTemplateJobPlan() {
    var strBtn = "<button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">Cancel</button>" +
                     "<button onclick=\"saveTemplateJobPlan();\" class=\"btn btn-primary ml-2\" > Save </button>";
    $('#modalSaveJobPlanTemplateConfirmationButton').html(strBtn);
}

function saveTemplateJobPlan() {
    var data = { 
            "name"              : $('#JobPlanTemplateName').val(),
            "data"              : getJobPlan(),
            "option_template"   : $('#txtChkJobPlanTempOption').val(),
            "template_id"       : $('#JobPlanTemplateList').val(),
            // "new_name"          : $('#jobPlanTemplateNewName').val(),
            "type"              : "C_SAVE_JOBPLAN_TEMPLATE"
            };
    var url = "index.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
  
    callServer(url,"json",data,onJobCentreResponse,null) ;
}
function popupLoadTemplateJobPlan() {
    var data = { 
                "type"                 : "C_VIEW_LOAD_JOBPLAN_TEMPLATE"
                };
    var url = "index.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
  
    callServer(url,"json",data,onJobCentreResponse,null) ;
}

function LoadTemplateJobPlan() {
    var data = { 
                "template_id"          : $('#JobPlanTemplateLoad').val(),
                "type"                 : "C_LOAD_JOBPLAN_TEMPLATE"
                };
    var url = "index.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
  
    callServer(url,"json",data,onJobCentreResponse,null) ;
}

function DeleteTemplateJobPlan() {
    $("#LoadJobPlanTemplateConfirmationView").modal("hide");
    var data = { 
            "template_id"          : $('#JobPlanTemplateLoad').val(),
        
            "type"                 : "C_DELETE_JOBPLAN_TEMPLATE"
            };
    var url = "index.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
  
    callServer(url,"json",data,onJobCentreResponse,null) ;
}

function populateJobPlanTemplateList() {
    var data = { 
                "type"                 : "C_VIEW_LOAD_JOBPLAN_TEMPLATE_LIST"
            };
    var url = "index.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;
  
    callServer(url,"json",data,onJobCentreResponse,null) ;
}

function addAccManager() {
    acc_mgr_idx++;

    var acc_mgr = '<select id="cmbAccMgr-'+acc_mgr_idx+'" class="col-lg-12 form-control cmbAccMgr">'+$('#cmbAccMgr-0').html()+'</select>';

    $('#acc-mgr-table').append(
        '<tr id="trAccMgr-' + acc_mgr_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtIdAccMgr" id="txtIdAccMgr'+acc_mgr_idx+'" value="-1">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">'+
                acc_mgr+
            '</td>' +


            '<td class="kt-datatable__cell">'+
                '<button title="Delete" onclick="javascript: deleteAccManager('+acc_mgr_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
            '</td>' +

        '</tr>'
    ); 
}

function deleteAccManager(idx) {
    $('#trAccMgr-'+idx).remove() ;
}

function addProjManager() {
    proj_mgr_idx++;

    var proj_mgr = '<select id="cmbProjMgr-'+proj_mgr_idx+'" class="col-lg-12 form-control cmbProjMgr">'+$('.cmbProjMgr').html()+'</select>';

    $('#proj-mgr-table').append(
        '<tr id="trProjManager-' + proj_mgr_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtIdProjMgr" id="txtIdProjMgr'+proj_mgr_idx+'" value="-1">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">'+
                proj_mgr+
            '</td>' +


            '<td class="kt-datatable__cell">'+
                '<button title="Delete" onclick="javascript: deleteProjManager('+proj_mgr_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
            '</td>' +

        '</tr>'
    ); 
}

function deleteProjManager(idx) {
    $('#trProjManager-'+idx).remove() ;
}

function addTechConsultant() {
    tech_cons_idx++;

    var tech_cons = '<select id="cmbTechConsultant-'+tech_cons_idx+'" class="col-lg-12 form-control cmbTechConsultant">'+$('.cmbTechConsultant').html()+'</select>';

    $('#tech-consultant-table').append(
        '<tr id="trTechConsultant-' + tech_cons_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtIdTechConsultant" id="txtIdTechConsultant'+tech_cons_idx+'" value="-1">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">'+
                tech_cons+
            '</td>' +


            '<td class="kt-datatable__cell">'+
                '<button title="Delete" onclick="javascript: deleteTechConsultant('+tech_cons_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
            '</td>' +

        '</tr>'
    ); 
}

function deleteTechConsultant(idx) {
    $('#trTechConsultant-'+idx).remove() ;
}

function addAppConsultant() {
    app_cons_idx++;

    var app_cons = '<select id="cmbAppConsultant-'+app_cons_idx+'" class="col-lg-12 form-control cmbAppConsultant">'+$('.cmbAppConsultant').html()+'</select>';

    $('#app-consultant-table').append(
        '<tr id="trAppConsultant-' + app_cons_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtIdAppConsultant" id="txtIdAppConsultant'+app_cons_idx+'" value="-1">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">'+
                app_cons+
            '</td>' +


            '<td class="kt-datatable__cell">'+
                '<button title="Delete" onclick="javascript: deleteAppConsultant('+app_cons_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
            '</td>' +

        '</tr>'
    ); 
}

function deleteAppConsultant(idx) {
    $('#trAppConsultant-'+idx).remove() ;
}

function addDeveloper() {
    dev_idx++;

    var dev = '<select id="cmbDeveloper-'+dev_idx+'" class="col-lg-12 form-control cmbDeveloper">'+$('#cmbDeveloper-0').html()+'</select>';

    $('#developer-table').append(
        '<tr id="trDeveloper-' + dev_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtIdDeveloper" id="txtIdDeveloper'+dev_idx+'" value="-1">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">'+
                dev+
            '</td>' +


            '<td class="kt-datatable__cell">'+
                '<button title="Delete" onclick="javascript: deleteDeveloper('+dev_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
            '</td>' +

        '</tr>'
    ); 
}

function deleteDeveloper(idx) {
    $('#trDeveloper-'+idx).remove() ;
}

function addCustProjSponsor() {
    cust_proj_sponsor_idx++;

    var cust_proj_sponsor = '<select id="cmbCustProjSponsor-'+cust_proj_sponsor_idx+'" class="col-lg-12 form-control cmbCustProjSponsor">'+$('#txtCentrePMName').html()+'</select>';

    $('#cust-proj-sponsor-table').append(
        '<tr id="trCustProjSponsor-' + cust_proj_sponsor_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtIdCustProjSponsor" id="txtIdCustProjSponsor'+cust_proj_sponsor_idx+'" value="-1">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">'+
                cust_proj_sponsor+
            '</td>' +


            '<td class="kt-datatable__cell">'+
                '<button title="Delete" onclick="javascript: deleteCustProjSponsor('+cust_proj_sponsor_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
            '</td>' +

        '</tr>'
    ); 
}

function deleteCustProjSponsor(idx) {
    $('#trCustProjSponsor-'+idx).remove() ;
}

function addCustProjAdvisor() {
    cust_proj_advisor_idx++;

    var cust_proj_advisor = '<select id="cmbCustProjAdvisor-'+cust_proj_advisor_idx+'" class="col-lg-12 form-control cmbCustProjAdvisor">'+$('#txtCentrePMName').html()+'</select>';

    $('#cust-proj-advisor-table').append(
        '<tr id="trCustProjAdvisor-' + cust_proj_advisor_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtIdCustProjAdvisor" id="txtIdCustProjAdvisor'+cust_proj_advisor_idx+'" value="-1">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">'+
                cust_proj_advisor+
            '</td>' +


            '<td class="kt-datatable__cell">'+
                '<button title="Delete" onclick="javascript: deleteCustProjAdvisor('+cust_proj_advisor_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
            '</td>' +

        '</tr>'
    ); 
}

function deleteCustProjAdvisor(idx) {
    $('#trCustProjAdvisor-'+idx).remove() ;
}

function addCustProjManager() {
    cust_proj_manager_idx++;

    var cust_proj_manager = '<select id="cmbCustProjMgr-'+cust_proj_manager_idx+'" class="col-lg-12 form-control cmbCustProjMgr">'+$('#txtCentrePMName').html()+'</select>';

    $('#cust-proj-mgr-table').append(
        '<tr id="trCustProjManager-' + cust_proj_manager_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtIdcmbCustProjMgr" id="txtIdcmbCustProjMgr'+cust_proj_manager_idx+'" value="-1">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">'+
                cust_proj_manager+
            '</td>' +


            '<td class="kt-datatable__cell">'+
                '<button title="Delete" onclick="javascript: deleteCustProjManager('+cust_proj_manager_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
            '</td>' +

        '</tr>'
    ); 
}

function deleteCustProjManager(idx) {
    $('#trCustProjManager-'+idx).remove() ;
}

function addCustProjMember() {
    cust_proj_member_idx++;

    var cust_proj_member = '<select id="cmbCustProjMember-'+cust_proj_member_idx+'" class="col-lg-12 form-control cmbCustProjMember">'+$('#txtCentrePMName').html()+'</select>';

    $('#cust-proj-member-table').append(
        '<tr id="trCustProjMember-' + cust_proj_member_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="form-control txtIdCustProjMember" id="txtIdCustProjMember'+cust_proj_member_idx+'" value="-1">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">' + 
            '</td>' +

            '<td class="kt-datatable__cell">'+
                cust_proj_member+
            '</td>' +


            '<td class="kt-datatable__cell">'+
                '<button title="Delete" onclick="javascript: deleteCustProjMember('+cust_proj_member_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
            '</td>' +

        '</tr>'
    ); 
}

function deleteCustProjMember(idx) {
    $('#trCustProjMember-'+idx).remove() ;
}

function showJobResources(resources){
    showAccManager(resources.account_manager);
    showProjManager(resources.project_manager);
    showTechConsultant(resources.tech_consultant);
    showAppConsultant(resources.app_consultant);
    showDeveloper(resources.developer);
    showCustProjSponsor(resources.cust_proj_sponsor);
    showCustProjAdvisor(resources.cust_proj_advisor);
    showCustProjManager(resources.cust_proj_manager);
    showCustProjMember(resources.cust_proj_member);
}

function showAccManager(obj) {
    // console.log(obj);
    // console.log(obj.length);
    if(obj.length > 0) {
        acc_mgr_idx = obj.length;
        $('#txtIdAccMgr0').val(obj[0].id);
        $('#cmbAccMgr-0').val(obj[0].user);
        
        if(obj.length > 1) {
            for(var i=1; i<obj.length; i++) {
                var acc_mgr = '<select id="cmbAccMgr-'+i+'" class="col-lg-12 form-control cmbAccMgr">'+$('#cmbAccMgr-0').html()+'</select>';
                $('#acc-mgr-table').append(
                    '<tr id="trAccMgr-' + i + '" class="kt-datatable__row">'+
                        '<td class="kt-datatable__cell" style="display:none;">' + 
                            '<input  class="form-control txtIdAccMgr" id="txtIdAccMgr'+i+'" value="'+obj[i].id+'">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                            acc_mgr +
                        '</td>' +
                        '<td class="kt-datatable__cell">'+
                            '<button title="Delete" onclick="javascript: deleteAccManager('+i+', this);" id="btnDeleteAccManager" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
                        '</td>' +
                    '</tr>'
                );                
                $('#cmbAccMgr-'+i).val(obj[i].user);
            }
        }
    }
}

function showProjManager(obj) {
    if(obj.length > 0) {
        proj_mgr_idx = obj.length;
        $('#txtIdProjMgr0').val(obj[0].id);
        $('#cmbProjMgr-0').val(obj[0].user);
        
        if(obj.length > 1) {
            for(var i=1; i<obj.length; i++) {
                var proj_mgr = '<select id="cmbProjMgr-'+i+'" class="col-lg-12 form-control cmbProjMgr">'+$('#cmbProjMgr-0').html()+'</select>';
                $('#proj-mgr-table').append(
                    '<tr id="trProjManager-' + i + '" class="kt-datatable__row">'+
                        '<td class="kt-datatable__cell" style="display:none;">' + 
                            '<input  class="form-control txtIdProjMgr" id="txtIdProjMgr'+i+'" value="'+obj[i].id+'">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                        proj_mgr +
                        '</td>' +
                        '<td class="kt-datatable__cell">'+
                        '<button title="Delete" onclick="javascript: deleteProjManager('+i+', this);" id="btnDeleteProjMgr" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
                        '</td>' +
                    '</tr>'
                );                
                $('#cmbProjMgr-'+i).val(obj[i].user);
            }
        }
    }
}

function showTechConsultant(obj) {
    if(obj.length > 0) {
        tech_consultant_idx = obj.length;
        $('#txtIdTechConsultant0').val(obj[0].id);
        $('#cmbTechConsultant-0').val(obj[0].user);
        
        if(obj.length > 1) {
            for(var i=1; i<obj.length; i++) {
                var tech_consultant = '<select id="cmbTechConsultant-'+ i +'" class="col-lg-12 form-control cmbTechConsultant">'+$('#cmbTechConsultant-0').html()+'</select>';
                $('#tech-consultant-table').append(
                    '<tr id="trTechConsultant-' + i + '" class="kt-datatable__row">'+
                        '<td class="kt-datatable__cell" style="display:none;">' + 
                            '<input  class="form-control txtIdTechConsultant" id="txtIdTechConsultant'+i+'" value="'+obj[i].id+'">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                        tech_consultant +
                        '</td>' +
                        '<td class="kt-datatable__cell">'+
                            '<button title="Delete" onclick="javascript: deleteTechConsultant('+i+', this);" id="btnDeleteTechConsultant" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
                        '</td>' +
                    '</tr>'
                );                
                $('#cmbTechConsultant-'+i).val(obj[i].user);
            }
        }
    }
}

function showAppConsultant(obj) {
    if(obj.length > 0) {
        app_consultant_idx = obj.length;
        $('#txtIdAppConsultant0').val(obj[0].id);
        $('#cmbAppConsultant-0').val(obj[0].user);
        
        if(obj.length > 1) {
            for(var i=1; i<obj.length; i++) {
                var app_consultant = '<select id="cmbAppConsultant-'+ i +'" class="col-lg-12 form-control cmbAppConsultant">'+$('#cmbAppConsultant-0').html()+'</select>';
                $('#app-consultant-table').append(
                    '<tr id="trAppConsultant-' + i + '" class="kt-datatable__row">'+
                        '<td class="kt-datatable__cell" style="display:none;">' + 
                            '<input  class="form-control txtIdAppConsultant" id="txtIdAppConsultant'+ i +'" value="'+obj[i].id+'">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                        app_consultant +
                        '</td>' +
                        '<td class="kt-datatable__cell">'+
                            '<button title="Delete" onclick="javascript: deleteAppConsultant('+i+', this);" id="btnDeleteAppConsultant" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
                        '</td>' +
                    '</tr>'
                );                 
                $('#cmbAppConsultant-'+i).val(obj[i].user);
            }
        }
    }
}

function showDeveloper(obj) {
    if(obj.length > 0) {
        dev_idx = obj.length;
        $('#txtIdDeveloper0').val(obj[0].id);
        $('#cmbDeveloper-0').val(obj[0].user);
        
        if(obj.length > 1) {
            for(var i=1; i<obj.length; i++) {
                var dev = '<select id="cmbDeveloper-'+i+'" class="col-lg-12 form-control cmbDeveloper">'+$('#cmbDeveloper-0').html()+'</select>';
                $('#developer-table').append(
                    '<tr id="trDeveloper-' + i + '" class="kt-datatable__row">'+
                        '<td class="kt-datatable__cell" style="display:none;">' + 
                            '<input  class="form-control txtIdDeveloper" id="txtIdDeveloper'+i+'" value="'+obj[i].id+'">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                        dev +
                        '</td>' +
                        '<td class="kt-datatable__cell">'+
                            '<button title="Delete" onclick="javascript: deleteDeveloper('+i+', this);" id="btnDeleteDeveloper" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
                        '</td>' +
                    '</tr>'
                );
                $('#cmbDeveloper-'+i).val(obj[i].user);
            }
        }
    }
}

function showCustProjSponsor(obj) {
    $('#cmbCustProjSponsor-0').html($('#txtCentrePMName').html());

    if(obj.length > 0) {
        cust_proj_sponsor_idx = obj.length;
        $('#txtIdCustProjSponsor0').val(obj[0].id);
        $('#cmbCustProjSponsor-0').val(obj[0].user);
        
        if(obj.length > 1) {
            for(var i=1; i<obj.length; i++) {
                var cust_proj_sponsor = '<select id="cmbCustProjSponsor-'+i+'" class="col-lg-12 form-control cmbCustProjSponsor">'+$('#txtCentrePMName').html()+'</select>';
                $('#cust-proj-sponsor-table').append(
                    '<tr id="trCustProjSponsor-' + i + '" class="kt-datatable__row">'+
                        '<td class="kt-datatable__cell" style="display:none;">' + 
                            '<input  class="form-control txtIdCustProjSponsor" id="txtIdCustProjSponsor'+i+'" value="'+obj[i].id+'">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                        cust_proj_sponsor +
                        '</td>' +
                        '<td class="kt-datatable__cell">'+
                            '<button title="Delete" onclick="javascript: deleteCustProjSponsor('+i+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
                        '</td>' +
                    '</tr>'
                );
                $('#cmbCustProjSponsor-'+i).val(obj[i].user);
            }
        }
    }
}

function showCustProjAdvisor(obj) {
    $('#cmbCustProjAdvisor-0').html($('#txtCentrePMName').html());

    if(obj.length > 0) {
        cust_proj_advisor_idx = obj.length;
        $('#txtIdCustProjAdvisor0').val(obj[0].id);
        $('#cmbCustProjAdvisor-0').val(obj[0].user);
        
        if(obj.length > 1) {
            for(var i=1; i<obj.length; i++) {
                var cust_proj_advisor = '<select id="cmbCustProjAdvisor-'+i+'" class="col-lg-12 form-control cmbCustProjAdvisor">'+$('#txtCentrePMName').html()+'</select>';
                $('#cust-proj-advisor-table').append(
                    '<tr id="trCustProjAdvisor-' + i + '" class="kt-datatable__row">'+
                        '<td class="kt-datatable__cell" style="display:none;">' + 
                            '<input  class="form-control txtIdCustProjAdvisor" id="txtIdCustProjAdvisor'+i+'" value="'+obj[i].id+'">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                        cust_proj_advisor +
                        '</td>' +
                        '<td class="kt-datatable__cell">'+
                            '<button title="Delete" onclick="javascript: deleteCustProjAdvisor('+i+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
                        '</td>' +
                    '</tr>'
                );
                $('#cmbCustProjAdvisor-'+i).val(obj[i].user);
            }
        }
    }
}

function showCustProjManager(obj) {
    $('#cmbCustProjMgr-0').html($('#txtCentrePMName').html());

    if(obj.length > 0) {
        cust_proj_manager_idx = obj.length;
        $('#txtIdcmbCustProjMgr0').val(obj[0].id);
        $('#cmbCustProjMgr-0').val(obj[0].user);
        
        if(obj.length > 1) {
            for(var i=1; i<obj.length; i++) {
                var cust_proj_manager = '<select id="cmbCustProjMgr-'+i+'" class="col-lg-12 form-control cmbCustProjMgr">'+$('#txtCentrePMName').html()+'</select>';
                $('#cust-proj-mgr-table').append(
                    '<tr id="trCustProjManager-' + i + '" class="kt-datatable__row">'+
                        '<td class="kt-datatable__cell" style="display:none;">' + 
                            '<input  class="form-control txtIdcmbCustProjMgr" id="txtIdcmbCustProjMgr'+i+'" value="'+obj[i].id+'">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                        cust_proj_manager +
                        '</td>' +
                        '<td class="kt-datatable__cell">'+
                            '<button title="Delete" onclick="javascript: deleteCustProjManager('+i+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
                        '</td>' +
                    '</tr>'
                );
                $('#cmbCustProjMgr-'+i).val(obj[i].user);
            }
        }
    }
}

function showCustProjMember(obj) {
    $('#cmbCustProjMember-0').html($('#txtCentrePMName').html());

    if(obj.length > 0) {
        cust_proj_member_idx = obj.length;
        $('#txtIdCustProjMember0').val(obj[0].id);
        $('#cmbCustProjMember-0').val(obj[0].user);
        
        if(obj.length > 1) {
            for(var i=1; i<obj.length; i++) {
                var cust_proj_member = '<select id="cmbCustProjMember-'+i+'" class="col-lg-12 form-control cmbCustProjMember">'+$('#txtCentrePMName').html()+'</select>';
                $('#cust-proj-member-table').append(
                    '<tr id="trCustProjMember-' + i + '" class="kt-datatable__row">'+
                        '<td class="kt-datatable__cell" style="display:none;">' + 
                            '<input  class="form-control txtIdCustProjMember" id="txtIdCustProjMember'+i+'" value="'+obj[i].id+'">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell">' + 
                        '</td>' +
                        '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                        cust_proj_member +
                        '</td>' +
                        '<td class="kt-datatable__cell">'+
                            '<button title="Delete" onclick="javascript: deleteCustProjMember('+i+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></button>'+
                        '</td>' +
                    '</tr>'
                );
                $('#cmbCustProjMember-'+i).val(obj[i].user);
            }
        }
    }
}

function showCompleteJobCentreModal(idx, obj){
    var job_task_id = $('#txtIdPlan'+idx).val();
    var job_centre_id = $('#txtCentreId').val();
    var date =$('#startdate-plan' + id).val()
    var date_end = $('#enddate-plan' + id).val()
    var hours = $('#hours-plan'+idx).val();

    console.log("task id : "+job_task_id);
    console.log("job centre id : "+job_centre_id);

    var data = { 
        "job_id"          : job_centre_id,
        "task_id"         : job_task_id,
        "date"            : date,
        "date_end"        : date_end,
        "hours"           : hours,
        "type"            : "CHECK_TASK_BALLANCE"
        };
    var url = "index.pzx?c=" + jobcentre_url + "&d=" + new Date().getTime() ;

    callServer(url,"json",data,onJobCentreResponse,null) ;
}