var C_ACTIVITY_FILTER                   = "502";
var C_ADD_ACTIVITY_VIEW                 = "503";
var C_ACTIVITY_UPDATE_VIEW              = "505";
var C_DELETE_ACTIVITY_HEADER            = "506";
var C_ACTIVITY_CUSTOMER                 = "507";
var C_ACTIVITY_DEDUCT                   = "508";
var C_ACTIVITY_PRINT_PREVIEW            = "509";
var C_ACTIVITY_TOGGLE_SIGNED            = "520";
var C_COMPLETE_TASK                     = "524";
var show_mode                           = false;
var activity_obj     = null;
var activity_idx     = 0;
$(document).ready(function() {
});
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 getJobList() {

    var buId = $("#cobActivityBuID").val();
    var data = { "type":  "GET_JOB_LIST", "buId" : buId , 'activity_id':$('#txtActivityID').val()} ;
    var url = "request.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onActivityResponse,activity_obj) ;

}
function getJobDetail() {
    var jobId = $("#txtActivityJobNumber").val();
    var data = { "type": C_GET + "_JOBDETAIL", "jobId" : jobId , 'activity_id':$('#txtActivityID').val()} ;
    var url = "request.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onActivityResponse,activity_obj) ;
}
function getAssignmentDetail(act_idx) {
    var assignId = $("#task-activity"+act_idx).val();
    var data = { "type": C_GET + "_ASSIGNDETAIL", "act_idx" : act_idx, "assignId" : assignId, "JobId":$('#txtActivityJobNumber').val()} ;
    var url = "request.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onActivityResponse,activity_obj) ;
}
// function toggleActivitySigned(id){
//     var data  = { "type": C_ACTIVITY_TOGGLE_SIGNED, 
//                   "id" : id} ;
//     var url  = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
//     callServer(url,"json",data,onActivityResponse,null) ;
// }
// function decimalNumber(temp){
//     var tt_over = temp.val();
//     temp.val((Math.round(tt_over * 100) / 100).toFixed(2));
// }
// function changeCustomer() {
//     var data  = { "type": C_ACTIVITY_CUSTOMER, 
//                   "customer_id" : $('#cobActivityCustomer').val()} ;
//     var url  = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
//     callServer(url,"json",data,onActivityResponse,null) ;
// }
// function changeDeduct() {
//     if ($('#cobActivityDeduct').val()!='1') {
//         $('#formProject').hide();
//     } else {
//         var data  = { "type": C_ACTIVITY_DEDUCT, 
//                   "customer_id" : $('#cobActivityCustomer').val()} ;
//         var url  = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
//         callServer(url,"json",data,onActivityResponse,null) ;
//     }
// }
function filterActivity(){
    var data = { "type": C_ACTIVITY_FILTER, 
                        "sorts": sorts,
                        "index": screen_index,
                    };
    var url  = "index.pzx?c=" + activity_url + "&t=" + C_ACTIVITY_FILTER  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onActivityResponse,null) ;
    return false;
}
function showAddActivity(){
    $('#btnActivityAdd').prop('disabled',false);

    screen_index++;
    showProgress("loading Service" ) ;
    var data = { "type": C_ADD_ACTIVITY_VIEW, "index": screen_index, } ;
    var url  = "index.pzx?c=" + activity_url + "&t=" + C_ADD_ACTIVITY_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onActivityResponse,null) ;
}
function addActivityHeader(conf) {
    saveActivityHeader(C_ADD,conf);
}
function updateActivityHeader(conf) {
    saveActivityHeader(C_UPDATE,conf) ; 
}

// function confirmPopUp(type,conf) {
//      if (mandatoryConfirm()){
//         var code =$('#txtActivityCode').val();
//         var func= (type=="a")?"addActivityHeader("+conf+")":"updateActivityHeader("+conf+")";
//         var strBtn = "<button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">Cancel</button>" +
//                          "<button onclick=\""+func+"\" class=\"btn btn-primary ml-2\" >Confirm </button>";
//         $("#confirmationMessageView").modal("show");
//         $('#modalConfirmationMessageViewTitle').html("Confirm Service");
//         $('#modalConfirmationMessageViewContent').html("Are you sure you want to confirm this Service (Code: "+code+") ?");
//         $('#modalcCnfirmationMessageButtonContent').html(strBtn);

//     }
// }

function saveActivityHeader(type,conf){
    $('#btnActivityAdd').prop('disabled','disabled');
    if (mandatoryActivity()){
        var data = {        "type"              : type,
                            "bu_id"             : $('#cobActivityBuID').val(),
                            "activity_id"       : $('#txtActivityID').val(),
                            "title"             : $('#txtActivityTitle').val(),
                            "site"              : $('#cobActivitySite').val(),
                            "bill"              : $('#cobActivityBill').val(),
                            "jobnumber"         : $('#txtActivityJobNumber').val() ,
                            "status"            : conf,
                            "user_id"           : $('#txtActivityUser').val(),
                            "code"              : $('#txtActivityCode').val(),
                            "cust_rep"          : $('#cobActivityCustRep').val(),
                            "remarks"           : $('#txtActivityRemarks').val(),
                            "tt_total"          : $("#txtTimeTrackerTotal").val(),
                            "tt_total_over"     : $("#txtTimeTrackerTotalOverride").val(),
                            "time_tracker"      : getTimeTrackerItem(),

                        };
        var url  = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
        if (conf==1) {
        $('#activityLoadingModal').modal('show');
        }
        // console.log(data);
        callServer(url,"json",data,onActivityResponse,activity_obj) ;
    } 
}

// function showMessage(type, message, title){
//     $("#modalMessageViewContent").html(message);
//     if(type == 'error')
//         $("#modalMessageHeaderContent").css({ "background-color": "#e20000" });
//     else if(type == 'success')
//         $("#modalMessageHeaderContent").css({ "background-color": "#3A78AD" });
//     else if(type == 'warning')
//         $("#modalMessageHeaderContent").css({ "background-color": "#FFD42A" });
//     $("#modalMessageViewTitle").html(title);
//     $("#messageView").modal("show");
// }

function showEditActivityHeader(id, obj) {
    $('#btnActivityAdd').prop('disabled',false);
    activity_obj = obj ;
    screen_index++;
    //showProgress("loading Service Header" ) ;
    
    var data  = { "type": C_ACTIVITY_UPDATE_VIEW, "id" : id, "sorts": sorts, "index": screen_index} ;
    var url   = "index.pzx?c=" + activity_url + "&t=" + C_ACTIVITY_UPDATE_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onActivityResponse,null) ;
}

function popupDeleteActivity(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_ACTIVITY_HEADER,
                "id": id
            } ;
            var url = "index.pzx?c=" + activity_url + "&t=" + C_DELETE_ACTIVITY_HEADER  + "&d=" + new Date().getTime() ; 
            callServer(url,"json",data,onActivityResponse,obj) ;
        }
    });
}

function getTimeTrackerItem() {
    
    var line_item = 1000;
   

     var arrays = [];
    $('#activity-list-table tr').each(function() { 

        var data = {     
                    "id"            : $('.txtActivityLine',this).val()  ,
                    "line_item"     : line_item  ,
                    "task"          : $('.txtActivityTask :selected',this).val()  ,
                    "desc"          : $('.txtActivityDesc',this).val()  ,
                    "phase"         : $('.txtActivityPhase',this).val()  ,
                    "start_date"    : $('.txtActivityStartDate',this).val()  ,
                    "end_date"      : $('.txtActivityEndDate',this).val()  ,
                    "start_time"    : $('.txtActivityStartTime',this).val()  ,  
                    "end_time"      : $('.txtActivityEndTime',this).val()  ,  
                    "hours"         : $('.txtActivityHours',this).val()  ,  
                    "break"         : $('.txtActivityBreak :selected',this).val()  ,  
                    "aftbreak"      : $('.txtActivityAftBreak',this).val()  ,  
                    "override"      : $('.txtActivityOverride',this).val()  ,  
                   };   

        arrays.push(data);
        line_item+=10;
    }); 

    return JSON.stringify(arrays) ;
}


//`ACTIVITY
function onActivityResponse(obj,resp){
    if (resp.status != C_OK ) {
        Swal.fire('error', resp.mesg, "Error");
        return false;
    }

    if (resp.type == C_ADD) {
        Swal.fire("Success", resp.mesg, "success");
        prevscreen();
        filterActivity();
    }  else if (resp.type == C_UPDATE) {
        Swal.fire("Success", resp.mesg, "success");
        prevscreen();
        filterActivity();
    }else if (resp.type == C_DELETE_ACTIVITY_HEADER) {
        Swal.fire("Success", resp.mesg, "success");
        filterActivity();
    } else if (resp.type == C_ADD_ACTIVITY_VIEW || resp.type == C_ACTIVITY_UPDATE_VIEW) {
        showScreen(resp);

       if (resp.type == C_ACTIVITY_UPDATE_VIEW) {
      
            showContentIndex(resp.data.all);
            $('#cobActivityBuID').val(resp.data.headerData.bu_id);

            $('#txtActivityUserName').val(resp.data.user_create);
            $('#txtActivityID').val(resp.data.headerData.id);
            $('#txtActivityTitle').val(resp.data.headerData.title);
            $('#cobActivityBill').val(resp.data.headerData.bill);
            $('#cobActivitySite').val(resp.data.headerData.site);

            $('#txtActivityJobNumber').html(resp.data.headerData.jobnumber_list) ;
            $('#txtActivityJobNumber').val(resp.data.headerData.jobnumber);

            $('#txtActivityJobName').val(resp.data.headerData.jobname);
            $('#txtActivityUser').val(resp.data.headerData.user_id);
            $('#txtActivityCode').val(resp.data.headerData.code);
            $('#txtActivityCustCode').val(resp.data.headerData.customer_code);
            $('#txtActivityCustName').val(resp.data.headerData.customer_name);
            // $('#txtActivityCustPMName').val(resp.data.headerData.customer_pm);

            $('#cobActivityCustRep').html(resp.data.headerData.custrep_opt) ;
            $('#cobActivityCustRep').val(resp.data.headerData.custrep) ;
            $('#cobActivityCustPMName').html(resp.data.headerData.customerpm_opt) ;
            $('#cobActivityCustPMName').val(resp.data.headerData.customerpm) ;

            $('#txtActivityCustPMName').val($('#cobActivityCustPMName :selected').text()) ;
           
            $('#txtActivityRemarks').val(resp.data.headerData.remarks) ;
            $("#txtActivityTaskComb").html(resp.data.headerData.task);

            var myObj = JSON.parse(resp.data.headerData.time_tracker);
            showTimeTracker(myObj);
           
            $('#txtTimeTrackerTotal').val(resp.data.headerData.tt_total);
            $('#txtTimeTrackerTotalOverride').val(resp.data.headerData.tt_total_over);
            
            var functionName = "updateActivityHeader(0)";
            // var functionConf = "confirmPopUp('u',1)";

            var strBtn = /*"<button type=\"button\" class=\"btn btn-success\" onclick=\"return "+functionConf+";\" style='float:left'>Confirm</button>"+*/
                        "<button type=\"button\" class=\"btn btn-secondary\" onclick=\"prevscreen();\" style='clear:both'>Cancel</button>"+
                        "<button id=\"btnActivityAdd\" class=\"btn btn-primary ml-3\" onclick=\"return "+functionName+";\">Save to Draft </button>";


            if (resp.data.headerData.status==1) {
                disableAll();
                var strBtn ="<button type=\"button\" class=\"btn btn-secondary\" onclick=\"prevscreen();\">Close</button>";
            }

            if (resp.data.headerData.signed==1) {
                disableAll();
                var strBtn ="<button type=\"button\" class=\"btn btn-secondary\" onclick=\"prevscreen();\">Close</button>";
            }

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

            // getChecklistActivity();
        } else {

            var functionName = "addActivityHeader(0)";
            // var functionConf = "confirmPopUp('a',1)";

            $('#txtActivityUserName').val(resp.data.user_create);

           var strBtn = /*"<button type=\"button\" class=\"btn btn-success\" onclick=\"return "+functionConf+";\" style='float:left'>Confirm</button>"+*/
                        "<button type=\"button\" class=\"btn btn-secondary\" onclick=\"prevscreen();\" style='clear:both'>Cancel</button>"+
                        "<button id=\"btnActivityAdd\" class=\"btn btn-primary ml-3\" onclick=\"return "+functionName+";\">Save to Draft </button>";

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

             // changeCustomer();
        }


    }else if(resp.type == C_ACTIVITY_FILTER || resp.type == C_SORT) {
        var wrapper = $('#activity_row_filter');
        wrapper.nextAll().remove();
        wrapper.after(resp.data);
    }
    else if(resp.type == C_ACTIVITY_CUSTOMER) {
        // $('#cobActivityLocation').html(resp.data.location);
        // $('#cobActivityCustomerContact').html(resp.data.contact);
        // changeDeduct();
    }
    else if(resp.type == C_ACTIVITY_DEDUCT) {
        // $('#formProject').show();
        // $('#cobActivityProject').html(resp.data);
    }    
    else if(resp.type == C_ACTIVITY_TOGGLE_SIGNED){
        // showMessage('success', resp.mesg, "Success");
        
        // var btnSigned = "<button title=\"Toggle Sign\" onclick=\"return toggleActivitySigned(" + resp.data.id  + ");\" id=\"btnToggleSigned\" class=\"btn " + (resp.data.signed == '0' ? 'btn-warning' : 'btn-success') + "\">" + 
        //                 (resp.data.signed == '0' ? 'No' : 'Yes') + "</button>";
           
        // $('#tdActivityHeaderSigned-'+resp.data.id).html(btnSigned) ;
    } else if (resp.type == 'GET_JOB_LIST') {
        
        $("#txtActivityJobNumber").html(resp.data);
        
    } else if (resp.type == C_GET + '_JOBDETAIL') {
        $("#txtActivityJobName").val(resp.data.jobname);
        $("#txtActivityCustCode").val(resp.data.custcode);
        $("#txtActivityCustName").val(resp.data.custname);
        
        $('#cobActivityCustRep').html(resp.data.pmname_opt) ;

        $('#cobActivityCustPMName').html(resp.data.pmname_opt) ;
        $('#cobActivityCustRep').val(resp.data.pmname) ;
      
        $('#txtActivityCustPMName').val($('#cobActivityCustRep :selected').text()) ;
       // $('#txtActivityCustPMName').val("");
        $("#txtActivityTaskComb").html(resp.data.task);
    } else if (resp.type == C_GET + '_ASSIGNDETAIL') {
      $("#phase-activity"+resp.data.act_idx).val(resp.data.phase);
      $("#desc-activity"+resp.data.act_idx).html(resp.data.desc);
    
      $("#startdate-activity"+resp.data.act_idx).val(resp.data.startdate);
      $("#enddate-activity"+resp.data.act_idx).val(resp.data.enddate);
      $("#starttime-activity"+resp.data.act_idx).val(resp.data.starttime);
      $("#endtime-activity"+resp.data.act_idx).val(resp.data.endtime);
      $("#balance-activity"+resp.data.act_idx).val(resp.data.balance);

        if(resp.data.status == "1"){
            $("#btnCompleteTask"+resp.data.act_idx).prop("disabled",true) ;
        }else{
            $("#btnCompleteTask"+resp.data.act_idx).prop("disabled",false)  ;
        }

      set(resp.data.act_idx);

    
    }else if (resp.type == "C_GET_CHECKLIST") {
        // $("#pnlChecklist").html(resp.data.html);
        // $("#countIndex").val(resp.data.countIndex);
    }else if (resp.type == "SEND_EMAIL_APPROVAL"){
        Swal.fire("Success", resp.mesg, "success");
         $('#emailActivityModal').modal('hide');
         filterActivity();
         //$('#activityLoadingModal').modal('hide');
    }else if(resp.type == "GET_CUST_EMAIL_REP"){
        $('#emailActivityModal').modal('show');
        $('#labelActivityCustRep').html(resp.data.repName);
        $('#activityEmailTo').val(resp.data.repMail);
        $('#activityEmailCC').val(resp.data.cc);
        $('#activityEmailRemarks').val(resp.data.remarks);
        $('#activity_id_email').val(resp.data.id_activity);
        
        if(resp.data.disabled==1){
            $('#btnSendEmailApproval').prop("disabled",true);
            
        }else{
            $('#btnSendEmailApproval').prop("disabled",false);
        }

    } else if (resp.type == C_COMPLETE_TASK) {
        $('#activity-list-table tr').each(function() {
           if($('.txtActivityTask',this).val() == resp.data.id && $('.txtActivityLinePlan',this).val() == resp.data.plan_id){
                $(".btnCompleteTask",this).prop("disabled",true) ;
           } 
        });

        Swal.fire("Success", resp.mesg, "success");
    }else if (resp.type == "C_SHOW_UPLOAD_ATTACH_VIEW" ) {
        // hideProgress(); 
        $("#uploadDocActivityView").modal("show");
        $('#modaluploadDocActivityContent').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_"+i+"'><td>"+
                                "Document Reference : &nbsp;&nbsp; <input style='margin-right:40px' size=17  type='text' name='txtDesc[]' value=''/>" +
                                "</td>" +
                                "<td>" + imgName +"</td>" +
                                "</tr>";
               
            }
            $("#activity_docs_upload").html(strHtml);
        });
        
        var strBtn = resp.data.button;
        $('#modaluploadDocActivityButtonContent').show().html(strBtn);
    }
}

function showPrintActPreview(id){
    var url = "index.pzx?c=" + activity_url + "&id=" + id +
            "&t=" + C_ACTIVITY_PRINT_PREVIEW + "&r=1";

    showReport(url) ;
}


function mandatoryActivity(){
    var actTitle=$('#txtActivityTitle').val();
    
    if (!actTitle) {
        Swal.fire('error', "Service Title can't be blank", "Error");
        $('#err_act_title').show();
        $('#btnActivityAdd').prop('disabled',false);
        return false;
    }

    var actTitle=$('#txtActivityCode').val();
    
    if (!actTitle) {
        Swal.fire('error', "Service # can't be blank", "Error");
        $('#btnActivityAdd').prop('disabled',false);
        return false;
    }
    return true;

}

function disableAll(){
    
    $('#txtActivityUserName').prop("disabled", "disabled");
    $('#txtActivityID').prop("disabled", "disabled");
    $('#txtActivityTitle').prop("disabled", "disabled");
    $('#cobActivityBill').prop("disabled", "disabled");
    $('#cobActivitySite').prop("disabled", "disabled");
    $('#txtActivityJobNumber').prop("disabled", "disabled");
    $('#txtActivityUser').prop("disabled", "disabled");
    $('#txtActivityCode').prop("disabled", "disabled");
    

}

function sendEmailApproval() {
    //$('#activityLoadingModal').modal('show');
    var data = { 
        "id"            : $('#activity_id_email').val(),
        "to_email"      : $('#activityEmailTo').val(),
        "cust_rep"      : $('#labelActivityCustRep').html(),
        "cc_email"      : $('#activityEmailCC').val(),
        "remarks"       : $('#activityEmailRemarks').val(),
        "type"          : "SEND_EMAIL_APPROVAL"
        };
    var url = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onActivityResponse,activity_obj) ;
}


function openEmailModal(id,custid,custrep,disabled) {
    var data = { 
        "id_activity"           : id,
        "id_cust_rep"           : custrep,
        "id_cust"               : custid,
        "disabled"              : disabled,
        "type"                  : "GET_CUST_EMAIL_REP"
        };

    var url = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;

    callServer(url,"json",data,onActivityResponse,activity_obj) ;

    
    
}

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

function showActivityDocs() {
    if($('#activity_docs_upload').text().trim() != "") {
        $("#btnActivityCancelUpload").prop('disabled',true);
        var url  = "index.pzx?c=" + activity_url + "&t=" + "C_SHOW_UPLOAD_ATTACH_DOC"  + "&d=" + new Date().getTime() + "&activity_id=" + $("#activity_id").val() ;
        $('#activity_docs_upload').show() ;
        ajaxUpload(upload_form,url,ActivityShowUploadEnd);

    }
    return false;
}

function ActivityShowUploadEnd(resp) {
    var msgArr      = resp.split("*");
    var status      = msgArr[0];
    var centreItems = msgArr[1];
    var error       = msgArr[2];
    
    if(status == "0") {
        $("#errorMsg").text("");
        $("#uploadMsg").text("");
        $("#activity_docs_upload").html("");
    } 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" +(i+1)+"'>";
                docItemHtml += "<td>" +docElements[1]+" (" + docElements[0] +")"+ "</td>";
                docItemHtml += "<td> <input name='txtDescs' type='text' value='" +docElements[2]+"' ></td>";
                docItemHtml += "<td style='width:40px;text-align:center;'><a class='fas fa-search' title='Preview' style='color:green; margin-top: 5px;' href='javascript:' onclick='downloadActivityFile(\"" + docElements[4] +"\", \""  + docElements[1] + "\")'></a>";
                docItemHtml += "&nbsp;&nbsp;&nbsp;<a class='fa fa-trash' title='Delete' style='color:red; margin-top: 5px;' href='javascript:' onclick='removeActivityFile(" + docElements[3] + ")'></a></td>";
                docItemHtml += "<input type='hidden' name='lblIds' value='"+ docElements[3] +"'>";
                docItemHtml += "</tr>";
    }
  
    $("#activity_docs_list tr:first").after(docItemHtml);
    $('#fileNameItem').html("");
    document.getElementById("form-upload-activity").reset();
}

function saveShowActivityDoc() {
    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",
                 "activity_id"  : $('#activity_id').val(), 
                 "docIds"   : docIds, 
                 "descList" : descList };
    var url  = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onActivityDocumentResponse,null) ;
}

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

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

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

function cancelActivityDocs() {
    $('#activity_docs_upload').html("");
    return false;
}
/** */

function addTimeTracker() {
    activity_idx++;

    var task  = '<select id="task-activity'+activity_idx+'" class="col-lg-12 form-control txtActivityTask" onchange="getAssignmentDetail('+activity_idx+');">'+$('#txtActivityTaskComb').html()+'</select>';
    var breakActivity = '<select id="break-activity'+activity_idx+'" class="col-lg-12 form-control txtActivityBreak" onchange="set('+activity_idx+');">'+$('#txtActivityBreakComb').html()+'</select>';

    var date_now = $('#txtActivityNowDate').val();
    var plan_id = $('#txtActivityJobNumber').val();

    $('#activity-list-table').append(
        '<tr id="trActivityList' + activity_idx + '" class="dnd-moved kt-datatable__row">'+
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="col-lg-12 form-control txtActivityLine" id="line-activity'+activity_idx+'" value="-1">' + 
            '</td>' +
            '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="col-lg-12 form-control txtActivityLinePlan" id="plan-line-activity'+activity_idx+'" value="'+plan_id+'">' + 
            '</td>' +

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

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                
                '<textarea class="col-lg-12 form-control txtActivityDesc" id="desc-activity'+activity_idx+'" col="2"></textarea>'+
            '</td>'+

            '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                '<input type="text" class="col-lg-12 form-control txtActivityPhase" id="phase-activity'+activity_idx+'">' + 
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<div class="input-group date">'+
                    '<input type="text" class="col-lg-12 form-control txtActivityStartDate"  placeholder="Select" id="startdate-activity' + activity_idx + '" onchange="set('+activity_idx+')" maxlength="10" value="'+date_now+'"/>'+
                    '<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="col-lg-12 form-control txtActivityEndDate"  placeholder="Select" id="enddate-activity' + activity_idx + '" maxlength="10" onchange="set('+activity_idx+')" value="'+date_now+'"/>'+
                    '<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;">'+
                '<input class="col-lg-12 form-control txtActivityStartTime" id="starttime-activity'+activity_idx+'" placeholder="Select time" type="text" onchange="set('+activity_idx+')" value="9:00 AM"/>'+
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                '<input class="col-lg-12 form-control txtActivityEndTime" id="endtime-activity'+activity_idx+'" placeholder="Select time" type="text" onchange="set('+activity_idx+')" value="6:00 PM"/>'+
            '</td>' +

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<input type="text" class="col-lg-12 form-control txtActivityHours" id="hours-activity'+activity_idx+'" disabled>' + 
            '</td>' +

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

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<input type="text" class="col-lg-12 form-control txtActivityAftBreak" id="aftbreak-activity'+activity_idx+'" value="9" disabled>' + 
            '</td>'+

            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<input type="text" class="col-lg-12 form-control txtActivityOverride" id="override-activity'+activity_idx+'" value="9" onkeyup="calculateTcMinute()">' + 
            '</td>'+
            '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                '<input type="text" class="col-lg-12 form-control txtActivityBalance" id="balance-activity'+activity_idx+'" value="0" disabled>' + 
            '</td>'+
            
            '<td class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;">'+
                '<button title="Delete" onclick="javascript: deleteActivityList('+activity_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></i></button>'+
            '</td>'+

            '<td class=\"kt-datatable__cell\" style="vertical-align:top;width:2%;padding-left:0;">'+
                '<button title="Complete Task" id="btnCompleteTask'+activity_idx+'" onclick="showCompleteModal('+plan_id+','+activity_idx+', this)" class="btn btn-success btn-sm btn-icon btn-icon-md btnCompleteTask"><i class="flaticon2-check-mark"></i></button>'+
            '</td>'+
        '</tr>'
    ); 

    //calculateTcMinute();

    var dteopt = {
        todayHighlight: true,
        orientation: "bottom left",
        
        format: 'dd/mm/yyyy',
        templates: {
            leftArrow: '<i class="la la-angle-left"></i>',
            rightArrow: '<i class="la la-angle-right"></i>'
        }
    }
    $("#btnCompleteTask"+activity_idx).prop("disabled",true) ;
    $(".txtActivityStartDate").datepicker(dteopt) ;
    $(".txtActivityEndDate").datepicker(dteopt) ;

    $('.txtActivityStartTime').timepicker();
    $('.txtActivityEndTime').timepicker();
    
    set(activity_idx);
}

function showTimeTracker(myObj){
    var id_max = [1000];

    show_mode = true;
    for (i in myObj) {
     
        id          = myObj[i].id;
        plan_id     = myObj[i].plan_id;
        id_task     = myObj[i].task;
        desc        = myObj[i].desc;
        phase       = myObj[i].phase;
        start_date  = myObj[i].start_date;
        date_end    = myObj[i].date_end;
        start_time  = myObj[i].start_time;
        end_time    = myObj[i].end_time;
        balance    = myObj[i].balance;
        hours       = parseFloat(myObj[i].hours).toFixed(2);
        breakAct    = myObj[i].break;
        aftbreak    = parseFloat(myObj[i].aftbreak).toFixed(2);
        override    = parseFloat(myObj[i].override).toFixed(2);    
        task_status = myObj[i].task_status;
        activity_idx = id;
        id_max.push(id);

        var task  = '<select id="task-activity'+activity_idx+'" class="col-lg-12 form-control txtActivityTask" onchange="getAssignmentDetail('+activity_idx+');">'+$('#txtActivityTaskComb').html()+'</select>';
        var breakActivity = '<select id="break-activity'+activity_idx+'" class="col-lg-12 form-control txtActivityBreak" onchange="set('+activity_idx+');">'+$('#txtActivityBreakComb').html()+'</select>';

        $('#activity-list-table').append(
            '<tr id="trActivityList' + activity_idx + '" class="dnd-moved kt-datatable__row">'+
                '<td class="kt-datatable__cell" style="display:none;">' + 
                    '<input  class="col-lg-12 form-control txtActivityLine" id="line-activity'+activity_idx+'" value="'+id+'">' + 
                '</td>' +
                '<td class="kt-datatable__cell" style="display:none;">' + 
                '<input  class="col-lg-12 form-control txtActivityLinePlan" id="plan-line-activity'+activity_idx+'" value="'+plan_id+'">' + 
            '</td>' +
                '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                    task + 
                '</td>' +

                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                   
                    '<textarea type="text" class="col-lg-12 form-control txtActivityDesc" id="desc-activity'+activity_idx+'" col="2">'+desc+'</textarea>'+
                '</td>'+

                '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                    '<input type="text" class="col-lg-12 form-control txtActivityPhase" id="phase-activity'+activity_idx+'" value="'+phase+'">' + 
                '</td>' +

                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<div class="input-group date">'+
                        '<input type="text" class="col-lg-12 form-control txtActivityStartDate"  placeholder="Select" id="startdate-activity' + activity_idx + '" onchange="set('+activity_idx+')" maxlength="10" value="'+start_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="col-lg-12 form-control txtActivityEndDate"  placeholder="Select" id="enddate-activity' + activity_idx + '" maxlength="10" onchange="set('+activity_idx+')" value="'+date_end+'"/>'+
                        '<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;">'+
                    '<input class="col-lg-12 form-control txtActivityStartTime" id="starttime-activity'+activity_idx+'" placeholder="Select time" type="text" onchange="set('+activity_idx+')" value="'+start_time+'"/>'+
                '</td>' +

                '<td class="kt-datatable__cell" style="vertical-align:top;">' + 
                    '<input class="col-lg-12 form-control txtActivityEndTime" id="endtime-activity'+activity_idx+'" placeholder="Select time" type="text" onchange="set('+activity_idx+')" value="'+end_time+'"/>'+
                '</td>' +

                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<input type="text" class="col-lg-12 form-control txtActivityHours" id="hours-activity'+activity_idx+'" value="'+hours+'" disabled>' + 
                '</td>' +

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

                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<input type="text" class="col-lg-12 form-control txtActivityAftBreak" id="aftbreak-activity'+activity_idx+'" value="'+aftbreak+'" disabled>' + 
                '</td>'+

                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<input type="text" class="col-lg-12 form-control txtActivityOverride" id="override-activity'+activity_idx+'" value="'+override+'" onkeyup="calculateTcMinute()">' + 
                '</td>'+
                '<td class="kt-datatable__cell" style="vertical-align:top;">'+
                    '<input type="text" class="col-lg-12 form-control txtActivityBalance" id="balance-activity'+activity_idx+'" value="'+balance+'" disabled>' + 
                '</td>'+
            
                '<td class=\"kt-datatable__cell\" style="width:40px;vertical-align:top;width:2%;">'+
                    '<button title="Delete" onclick="javascript: deleteActivityList('+activity_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md"><i class="fa fa-trash"></i></button>'+
                '</td>'+
                '<td class=\"kt-datatable__cell\" style="width:40px;vertical-align:top;width:2%;padding-left:0;">'+
                    '<button title="Complete Task"  id="btnCompleteTask'+activity_idx+'" onclick="showCompleteModal('+plan_id+','+activity_idx+', this)" class="btn btn-success btn-sm btn-icon btn-icon-md btnCompleteTask"><i class="flaticon2-check-mark"></i></button>'+
                '</td>'+
            '</tr>'
        ); 
            
        if(task_status == "1"){
            $("#btnCompleteTask"+activity_idx).prop("disabled",true) ;
        }else{
            $("#btnCompleteTask"+activity_idx).prop("disabled",false) ;
        }

        $("#task-activity"+activity_idx).val(id_task);
        $("#break-activity"+activity_idx).val(breakAct);

        //calculateTcMinute();

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

        $(".txtActivityStartDate").datepicker(dteopt) ;
        $(".txtActivityEndDate").datepicker(dteopt) ;

        $('.txtActivityStartTime').timepicker();
        $('.txtActivityEndTime').timepicker();
        
        //set(activity_idx);

        //===
        activity_idx = parseInt(id) +10;
    }
    show_mode = false;
    activity_idx = Math.max.apply(null, id_max);

}

var Hour = 0;
var Days = 0; 
var fHour = 0; 
var Break = 0; 
var AftBreak = 0; 
var detailOverride = 0; 

function set(act_idx) {
    //Calculate Hour
    
    if(!show_mode){
        var startTime = moment.utc($('#starttime-activity'+act_idx).val(), "HH:mm:ss a");
        var endTime   = moment.utc($('#endtime-activity'+act_idx).val(), "HH:mm:ss a");
        Hour          = moment.duration(endTime.diff(startTime)).asHours();
        Hour          = parseFloat(Hour).toFixed(2);
        
    
        if (Hour<0) {
            
            return false;
        }
    
        
        //Calculate Day
        var startDate = moment($('#startdate-activity'+act_idx).val(), "DD/MM/YYYY");
        var endDate   = moment($('#enddate-activity'+act_idx).val(), "DD/MM/YYYY");
        Days          = endDate.diff(startDate, 'days');
       
        if (Days+1<=0) {
           
            return false;
        }
    
        fHour = getTimeTrackerFinalHourUpdate(Hour, Days);
        Break = getTimeTrackerBreakUpdate(Days,act_idx);
      
        AftBreak = fHour-Break;
        $('#hours-activity'+act_idx).val(fHour);
        $('#aftbreak-activity'+act_idx).val(parseFloat(AftBreak).toFixed(2));
        $('#override-activity'+act_idx).val(parseFloat(AftBreak).toFixed(2));
     
        calculateTcMinute();
    }
    
}

function getTimeTrackerFinalHourUpdate(Hour, Days){
    //Final Hour
    var fHour = Hour*(Days+1);
        fHour = parseFloat(fHour).toFixed(2);
        
    return fHour;
}

function getTimeTrackerBreakUpdate(Days,idx){
    return parseFloat($('#break-activity'+idx).val() * (Days + 1)/60).toFixed(2);
}

function calculateTcMinute(){
    var totalHour=0;
    var totalOverride = 0;
   $('#activity-list-table tr').each(function() {
       var Hour=parseFloat($('.txtActivityAftBreak', this).val());
      
       if(!Hour){Hour = 0;}
       totalHour += Hour;        
       
       var Override=parseFloat($('.txtActivityOverride', this).val());
       if(!Override){Override = 0;}
       totalOverride += Override;       
    });
    
   $('#txtTimeTrackerTotal').val(parseFloat(totalHour).toFixed(2));
   $('#txtTimeTrackerTotalOverride').val(parseFloat(totalOverride).toFixed(2));
}

function onOverrideToChange(act_idx){
    // var Hour = getTimeTrackerHourUpdate();
    if (Hour <= 0) {
        $('#override-activity'+act_idx).val("0.00");
    }

    // var Days = getTimeTrackerDaysUpdate();
    if (Days+1 <= 0) {
        $('#override-activity'+act_idx).val("0.00");
    }

    fHour = getTimeTrackerFinalHourUpdate(Hour, Days);
    Break = getTimeTrackerBreakUpdate(Days,act_idx);

    //Calculate After Break
    AftBreak        = fHour-Break;
    detailOverride  = parseFloat(AftBreak).toFixed(2);

    $('#aftbreak-activity'+act_idx).val(parseFloat(AftBreak).toFixed(2));
    $('#override-activity'+act_idx).val(detailOverride);
    calculateTcMinute();
}


function deleteActivityList(idx) {
    $('#trActivityList'+idx).remove() ;
    calculateTcMinute();
}
function showCompleteModal(plan_id,idx, obj){
    Swal.fire({
       title: "Complete Task Confirmation",
       text: "Confirm you want to complete this task?",
       type: "warning",
       showCancelButton: true,
       confirmButtonText: "Yes",
       confirmButtonColor: '#26C281',
   }).then(function(result) {
       if (result.value) {
            var id =  $('#task-activity'+idx).val();
            var data = { 
            "id"            : id,
            "idx"           : idx,
            "plan_id"       : plan_id,
            "type"          : C_COMPLETE_TASK
            };
            var url = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
            callServer(url,"json",data,onActivityResponse,activity_obj) ;
       }
   });
}
