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 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 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(){
    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-default\" data-dismiss=\"modal\">Cancel</button>" +
//                          "<button onclick=\""+func+"\" class=\"btn btn-primary\" >Confirm </button>";
//         $('#modalcCnfirmationMessageButtonContent').html(strBtn);
//         $('#modalConfirmationMessageViewContent').html("Are you sure you want to confirm this Service (Code: "+code+") ?");
//         $('#modalConfirmationMessageViewTitle').html("Confirm Service");
//         $("#confirmationMessageView").modal("show");

//     }
// }
function saveActivityHeader(type,conf){
     
    if (mandatoryActivity()){
        var data = {        "type"              : type,
                            "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(),
                            
                            // "coy_id"            : $('#cobActivityBu').val(), 
                            // "customer"          : $('#cobActivityCustomer').val(),
                            // "location"          : $('#cobActivityLocation').val(),
                            // "activity_type"     : $('#cobActivityType').val(),
                            // "status_project"    : $('#cobActivityStatus').val(),
                            // "desc"              : $('#txtActivityTask').val(),
                            // "deduct"            : $('#cobActivityDeduct').val(),
                            // "contact_id"        : $('#cobActivityCustomerContact').val(),
                            // "project_id"        : $('#cobActivityProject').val(),
                            // "et_total"          : $("#txtExpenseTrackerTotal").html(),
                            // "time_tracker"      : getTimeTrackerItem(),
                            // "expense_tracker"   : getExpenseTrackerItem(),
                            // "checklist_value"   : getChecklistVal()

                        };
        var url  = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
        if (conf==1) {
        $('#activityLoadingModal').modal('show');
        }
        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) {
    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?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes",
        cancelButtonColor: '#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 deleteActivity(id, obj) {
//     $("#deleteConfirmationView").modal("hide");
//     var data = { 
//             "id"            : id,
//             "type"          : C_DELETE_ACTIVITY_HEADER
//             };
//     var url = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
//     callServer(url,"json",data,onActivityResponse,obj) ;
// }

// function addTimeTracker(){

//     if (mandatoryTimeTracker()) {
//         var checkLine=getItemTimeTrackerTempLine();

//         if (checkLine) {
//             var req_line=parseInt(checkLine)+10;
//         }else{
//             var  req_line=1000; 
//         }


//         var btnActTime="<a class=\"glyphicon glyphicon-pencil btnPencil\" title=\"Edit\" style=\"color:orange; margin-top: 5px; padding-right:10px\" href=\"javascript:\" onclick=\"showTimeTrackerTempEditItem("+req_line+")\"></a>"+               
//                             "<a class=\"glyphicon glyphicon-trash btnTrash\" title=\"Remove\" onclick=\"return deleteItemTimeTracker("+ req_line+");\" style=\"color:red; margin-top: 5px;\"></a>";
        
//         var Hour = getTimeTrackerHourUpdate();
//         if (/*endTime<startTime || */Hour<=0) {
//             showMessage('error', "Time not valid, End Time must more than Start Time.", "Warning");
//             return false;
//         }
        
//         var Days = getTimeTrackerDaysUpdate();
//         if (Days+1<=0) {
//             showMessage('error', "Date not valid, End Date must more than Start Date.", "Warning");
//             return false;
//         }

//         var fHour = getTimeTrackerFinalHourUpdate(Hour, Days);
        
//         var Break = getTimeTrackerBreakUpdate(Days);

//         //Calculate After Break
//         var AftBreak = fHour-Break;
        
//         var detailOverride = parseFloat($('#txtTimeTrackerTotalDetailOverride').val()).toFixed(2);
        
//         var line_exist = $('#txtTimeTrackerLine').val();
//         if (line_exist=='') {
//             $('#tbl-activity-time-tracker').append("<tr id=\"item-time-tracker-"+ req_line +"\">" + 
//                             "<td id=\"txtTcLine-"+ req_line +"\" class=\"txtTcLine\">"+ req_line +"</td>" +
//                             "<td id=\"txtTcAssignId-"+ req_line +"\">"+ $('#txtActivityJobAssignment :selected').val() +"</td>" +
//                             "<td id=\"txtTcAssignDesc-"+ req_line +"\">"+ $('#txtActivityJobAssignment :selected').text() +"</td>" +
//                             "<td id=\"txtTcDesc-"+ req_line +"\">"+ $('#txtTimeTrackerDesc').val() +"</td>" +
//                             "<td id=\"txtTcPhase-"+ req_line +"\" class=\"txtTcPhase\">"+ $('#txtTimeTrackerPhase').val() +"</td>" +
//                             "<td id=\"txtTcDate-"+ req_line +"\" class=\"txtTcDate\">"+ $('#txtTimeTrackerDate').val() +"</td>" +
//                             "<td id=\"txtTcEndDate-"+ req_line +"\" class=\"txtTcEndDate\">"+ $('#txtTimeTrackerEndDate').val() +"</td>" +
//                             "<td id=\"txtTcStart-"+ req_line +"\">"+ $('#txtTimeTrackerStart').val() +"</td>" +
//                             "<td id=\"txtTcEnd-"+ req_line +"\">"+ $('#txtTimeTrackerEnd').val() +"</td>" +
//                             "<td id=\"txtTcMinute-"+ req_line +"\" class=\"txtTcMinute\">"+fHour+"</td>"+
//                             "<td id=\"txtTcBreak-"+ req_line +"\" class=\"txtTcBreak\">"+Break+"</td>"+
//                             "<td id=\"txtTcAftBreak-"+ req_line +"\" class=\"txtTcAftBreak\">"+parseFloat(AftBreak).toFixed(2)+"</td>"+
//                             "<td id=\"txtTcOverride-"+ req_line +"\" class=\"txtTcOverride\">"+detailOverride+"</td>"+
//                             "<td style=\"display:none;\" id=\"txtTcChecklist-"+ req_line +"\" class=\"txtTcChecklist\">0</td>"+
//                             "<td>"+btnActTime+"</td>"+
//                             "<td ></td>"+
//                             "</tr>");
//         } else {
//             $('#btnAddTimeTracker').html('Add');
//             $('#txtTcAssignId-'+line_exist).html($('#txtActivityJobAssignment :selected').val());
//             $('#txtTcAssignDesc-'+line_exist).html($('#txtActivityJobAssignment :selected').text());
//             $('#txtTcDesc-'+line_exist).html($('#txtTimeTrackerDesc').val());
//             $('#txtTcPhase-'+line_exist).html($('#txtTimeTrackerPhase').val());
//             $('#txtTcDate-'+line_exist).html($('#txtTimeTrackerDate').val());
//             $('#txtTcEndDate-'+line_exist).html($('#txtTimeTrackerEndDate').val());
//             $('#txtTcStart-'+line_exist).html($('#txtTimeTrackerStart').val());
//             $('#txtTcEnd-'+line_exist).html($('#txtTimeTrackerEnd').val());
//             $('#txtTcMinute-'+line_exist).html(fHour);
//             $('#txtTcBreak-'+line_exist).html(Break);
//             $('#txtTcAftBreak-'+line_exist).html(parseFloat(AftBreak).toFixed(2));
//             $('#txtTcOverride-'+line_exist).html(detailOverride);
//             $('#txtTcChecklist-'+line_exist).html($('#checklistId').val());
            
//         }

//         calculateTcMinute();
//         //reset form
//         resetTimeTracker();
//         //getChecklistActivity();
//         //
//     }
// }

// function getItemTimeTrackerTempLine() {   
//     line=0;
//     $('#tbl-activity-time-tracker tbody tr').each(function() { 
//             line = $('.txtTcLine', this).html();
//         });
//         return line;
// }

// function deleteItemTimeTracker(line){
//    $('#item-time-tracker-'+line).remove();
//    calculateTcMinute();
// }

// function showTimeTrackerTempEditItem(line){

//     $('#txtTimeTrackerLine').val(line);
//     $('#txtActivityJobAssignment').val($('#txtTcAssignId-'+line).text());
//     $('#txtTimeTrackerDesc').val($('#txtTcDesc-'+line).html());
//     $('#txtTimeTrackerPhase').val($('#txtTcPhase-'+line).html());
//     $('#txtTimeTrackerDate').val($('#txtTcDate-'+line).html());
//     $('#txtTimeTrackerEndDate').val($('#txtTcEndDate-'+line).html());
    
//     var Days = getTimeTrackerDaysUpdate();

//     $('#txtTimeTrackeBreak').val(parseFloat($('#txtTcBreak-'+line).html()) / (Days + 1) *60);
//     // $('#txtTimeTrackerStart').val($('#txtTcStart-'+line).html());
//     // $('#txtTimeTrackerEnd').val($('#txtTcEnd-'+line).html());
//     $('#txtTimeTrackerStart').timepicker('setTime',  $('#txtTcStart-'+line).html());
//     $('#txtTimeTrackerEnd').timepicker('setTime', $('#txtTcEnd-'+line).html());
    
//     $('#txtTimeTrackerTotalDetailOverride').val(parseFloat($('#txtTcOverride-'+line).html()).toFixed(2));
    
//     $('#btnAddTimeTracker').html('Update');

// }

// function to24Hour(str) {
//     var tokens = /([10]?\d):([0-5]\d) ([ap]m)/i.exec(str);
//     if (tokens == null) { return null; }
//     if (tokens[3].toLowerCase() === 'pm' && tokens[1] !== '12') {
//         tokens[1] = '' + (12 + (+tokens[1]));
//     } else if (tokens[3].toLowerCase() === 'am' && tokens[1] === '12') {
//         tokens[1] = '00';
//     }
//     //return tokens[1] + ':' + tokens[2];
//     return tokens[1] + tokens[2];
// }

// function addExpenseTracker(){

//     if (mandatoryExpenseTracker()) {

//         var checkLine=getExpenseTempLine();

//         if (checkLine) {
//             var req_line=parseInt(checkLine)+10;
//         }else{
//             var  req_line=1000; 
//         }

//         var line_exist = $('#txtExpenseTrackerLine').val();
//         if (line_exist=='') {

//             var btnActTime="<a class=\"glyphicon glyphicon-pencil btnPencil\" title=\"Edit\" style=\"color:orange; margin-top: 5px; padding-right:10px\" href=\"javascript:\" onclick=\"showExpenseTrackerTempEditItem("+req_line+")\"></a>"+               
//                                 "<a class=\"glyphicon glyphicon-trash btnTrash\" title=\"Remove\" onclick=\"return deleteItemExpenseTracker("+ req_line+");\" style=\"color:red; margin-top: 5px;\"></a>";

//             $('#tbl-activity-expense-tracker').append("<tr id=\"item-expense-tracker-"+ req_line +"\">" + 
//                             "<td id=\"txtExLine-"+ req_line +"\" class=\"txtExLine\">"+ req_line +"</td>" +
//                             "<td id=\"txtExItem-"+ req_line +"\">"+ $('#cobExpenseTrackerItem option:selected').text() +"</td>" +
//                             "<td id=\"txtExReceipt-"+ req_line +"\">"+ $('#txtExpenseTrackerReceipt').val() +"</td>" +
//                             "<td id=\"txtExAmountAftTax-"+ req_line +"\" class=\"txtExAmountAftTax\">"+ $('#txtAddExFinalAmount').val() +"</td>" +
//                             "<td id=\"txtExDesc-"+ req_line +"\">"+ $('#txtExpenseTrackerDesc').val() +"</td>" +
//                             "<td id=\"txtExType-"+ req_line +"\">"+ $('#cobExpenseTrackerType option:selected').text() +"</td>" +
//                             "<td id=\"txtExGts-"+ req_line +"\">"+$('#txtAddExTaxAmount').val()+"</td>" +
//                             "<td>"+btnActTime+"</td>"+
//                             "<td style='display:none'>"+
//                                 "<input id=\"txtExItemVal-"+ req_line +"\" value=\""+$('#cobExpenseTrackerItem').val()+"\"/>"+
//                                 "<input id=\"txtExTypeVal-"+ req_line +"\" value=\""+$('#cobExpenseTrackerType').val()+"\"/>"+
//                                 "<input id=\"txtExTaxIdVal-"+ req_line +"\" value=\""+$('#cobAddExTaxId').val()+"\"/>"+
//                                 "<input id=\"txtExAmountVal-"+ req_line +"\" value=\""+$('#txtExpenseTrackerAmount').val()+"\"/>"+
//                             "</td>"+
//                             "</tr>");
//         } else {
//             $('#btnAddExpenseTracker').html('Add');
//             $('#txtExItem-'+line_exist).html($('#cobExpenseTrackerItem option:selected').text());
//             $('#txtExReceipt-'+line_exist).html($('#txtExpenseTrackerReceipt').val());
//             $('#txtExAmountAftTax-'+line_exist).html($('#txtAddExFinalAmount').val());
//             $('#txtExDesc-'+line_exist).html($('#txtExpenseTrackerDesc').val());
//             $('#txtExType-'+line_exist).html($('#cobExpenseTrackerType option:selected').text());
//             $('#txtExGts-'+line_exist).html($('#txtAddExTaxAmount').val());
//             $('#txtExItemVal-'+line_exist).val($('#cobExpenseTrackerItem').val());
//             $('#txtExTypeVal-'+line_exist).val($('#cobExpenseTrackerType').val());
//             $('#txtExTaxIdVal-'+line_exist).val($('#cobAddExTaxId').val());
//             $('#txtExAmountVal-'+line_exist).val($('#txtExpenseTrackerAmount').val());
//         }

//         calculateExTotal();
//         resetExpenseTracker();
//     }
// }

// function resetExpenseTracker(){
//     $('#cobExpenseTrackerItem').val($("#cobExpenseTrackerItem option:first").val());
//     $('#txtExpenseTrackerReceipt').val('');
//     $('#cobExpenseTrackerType').val($("#cobExpenseTrackerType option:first").val());
//     $('#txtExpenseTrackerAmount').val(0.00);
//     $('#cobAddExTaxId').val($("#cobAddExTaxId option:first").val());
//     $('#txtExpenseTrackerDesc').val('');
//     $('#txtExpenseTrackerLine').val('');
//     updatExTaxPercentage();
//     recalculateExAmount();
// }


// function getExpenseTempLine() {   
//     line=0;
//     $('#tbl-activity-expense-tracker tbody tr').each(function() { 
//             line = $('.txtExLine', this).html();
//         });
//         return line;
// }

// function deleteItemExpenseTracker(line){
//    $('#item-expense-tracker-'+line).remove();
//    calculateExTotal();
// }

// function showExpenseTrackerTempEditItem(line){

//     $('#btnAddExpenseTracker').html('Update');
//     $('#txtExpenseTrackerLine').val(line)
//     $('#txtExpenseTrackerReceipt').val($('#txtExReceipt-'+line).html());
//     $('#txtExpenseTrackerDesc').val($('#txtExDesc-'+line).html());
//     $('#txtExpenseTrackerAmount').val($('#txtExAmountVal-'+line).val());

//     $('#cobExpenseTrackerItem').val($('#txtExItemVal-'+line).val())
//     $('#cobExpenseTrackerType').val($('#txtExTypeVal-'+line).val())
//     $('#cobAddExTaxId').val($('#txtExTaxIdVal-'+line).val())
//      updatExTaxPercentage();
//     recalculateExAmount();


// }


// function calculateExTotal(){
//     var total=0;
//    $('#tbl-activity-expense-tracker tbody tr').each(function() {
//                amount=parseFloat($('.txtExAmountAftTax', this).html());
//                if(!amount){amount = 0;}
//                total += amount;           
//             });

//    $('#txtExpenseTrackerTotal').html(parseFloat(total).toFixed(2));
  

// }

// function updatExTaxPercentage(){
//     $('#cobAddExTaxPercentage').val($('#cobAddExTaxId').val());
//     recalculateExAmount();
// }

// function recalculateExAmount(){

//     if (isNaN($('#txtExpenseTrackerAmount').val()) || $('#txtExpenseTrackerAmount').blank()){
//         $('#txtExpenseTrackerAmount').val('0.00');
//     } 
    
//     var amount=parseFloat($('#txtExpenseTrackerAmount').val());
//     var taxPercentage = parseFloat($('#cobAddExTaxPercentage option:selected').text());
//     if (isNaN(taxPercentage)){
//         taxPercentage = 0.0;
//     }
//     var taxAmount = amount * taxPercentage / 100;
//     var total = amount + taxAmount;

    
//     $('#txtExpenseTrackerAmount').val((Math.round(amount * 100) / 100).toFixed(2));
//     $('#txtAddExFinalAmount').val((Math.round(total * 100) / 100).toFixed(2));
//     $('#txtAddExTaxAmount').val((Math.round(taxAmount * 100) / 100).toFixed(2));

// }

// function getTimeTrackerItem() {
//     var sep = "" ;
//     var id = "" ;
//     var lines ="";
//     var line_item = 1000;
   
    
//     $('#tbl-activity-time-tracker tbody tr').each(function() { 
//         var init=0;

//         //line = $('.txtTcLine', this).val();
//         assignId = $(this).find("td").eq(1).html();
//         desc = $(this).find("td").eq(3).html();
//         tmSt = $(this).find("td").eq(7).html();
//         tmEnd = $(this).find("td").eq(8).html();
//         hour = $('.txtTcMinute', this).html();
//         tmbreak = $('.txtTcBreak', this).html();
//         tmAftbreak = $('.txtTcAftBreak', this).html();
//         phase = $('.txtTcPhase', this).html();
//         date = $('.txtTcDate', this).html();
//         end_date = $('.txtTcEndDate', this).html();
//         override = $('.txtTcOverride', this).html();

//         console.log(tmSt);
//         console.log(tmEnd);
//         lines = lines + sep + id + '~' + line_item + '~' + assignId + '~' + desc + '~' + tmSt + 
//                 '~' + tmEnd + '~' + hour+ '~' +tmbreak+ '~' +tmAftbreak+ '~' +phase+ '~' +date+'~'+end_date+'~'+override;
//         sep = "|" ;
//         line_item+=10;

//     }); 
//     return lines;
// }

// function getExpenseTrackerItem() {
//     var sep = "" ;
//     var id = "" ;
//     var lines ="";
//     var line_item = 1000;
   
    
//     $('#tbl-activity-expense-tracker tbody tr').each(function() { 
//         var init=0;

//         line = $('.txtExLine', this).html();
//         receipt = $(this).find("td").eq(2).html();
//         amount_aft_tax = $(this).find("td").eq(3).html();
//         desc = $(this).find("td").eq(4).html();
//         tax = $(this).find("td").eq(6).html();
//         item = $('#txtExItemVal-'+line, this).val();
//         type = $('#txtExTypeVal-'+line, this).val();
//         taxid = $('#txtExTaxIdVal-'+line, this).val();
//         amount = $('#txtExAmountVal-'+line, this).val();

//         lines = lines + sep + id + '~' + line_item + '~' + receipt + '~' + amount_aft_tax + 
//                 '~' + desc + '~' + tax + '~' + item + '~' + type+ '~' + taxid + '~' + amount;
//         sep = "|" ;
//         line_item+=10;

//     }); 
//     return lines;
// }


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

    if (resp.type == C_ADD) {
        // $("#confirmationMessageView").modal("hide");
        // showMessage('success', resp.mesg, "Success");
        // var draft = "<strong style=\"color:blue\">Draft</strong>";
        // var conf = "<strong style=\"color:green\">Confirm</strong>";

       
        // if (resp.data.status==0) {
        //     status=draft;
        //     var btnDel="<button title=\"Delete\" onclick=\"javascript:popupDeleteActivity("+resp.data.id+", this);\" id=\"btnDelete\" data-toggle=\"modal\" class=\"btn btn-danger glyphicon glyphicon-trash btn-sm\"></button>";
        // } else {
        //     status=conf;
        //     var btnDel="";
        // }
        
        // 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>";

        // var job_number = $('#txtActivityJobNumber :selected').text().split("-");
        // var customer_name  = $('#cobActivityCustomer :selected').text();
        // $('#activity-table tbody:first tr:first').after(
        //         "<tr id='activity-rows-" + resp.data.id + "'>" + 
        //         "<td style='display:none'>" + resp.data.id + "</td>" + 
        //         "<td id='tdActivityHeaderSigned" + resp.data.id + "'>"  + btnSigned + "</td>" +
        //         "<td>" + $('#txtActivityCode').val() + "</td>" +
        //         "<td>" + job_number[0] + "</td>" +
        //         "<td>" + $('#txtActivityDate').val() + "</td>" +
        //         "<td>" + customer_name + "</td>" +
        //         "<td>" + $('#txtActivityTitle').val() + "</td>" +
        //         "<td>" + $('#cobActivityDeduct :selected ').text() + "</td>" + 
        //         "<td>" + status + "</td>" + 
        //         "<td>" + $('#txtActivityUserName').val() + "</td>" + 
        //         "<td><div><button title=\"View\" onclick=\"return showEditActivityHeader("+resp.data.id+",this);\" id=\"btnEdit\" class=\"btn btn-primary glyphicon glyphicon-edit btn-sm\"></button>" +
        //         btnDel +
        //         "<button title=\"Print Preview\" onclick=\"javascript:showPrintActPreview("+resp.data.id+");\" id=\"btnPrintPreview\"  class=\"btn btn-default glyphicon glyphicon-print btn-sm\"></button>" +
        //         "<button title=\"Upload Additional Doc\" onclick=\"javascript:showActivityDocsView("+resp.data.id+");\" id=\"btnUploadAddDocSR\"  class=\"btn btn-info glyphicon glyphicon-file btn-sm\"></button>" +
        //         "</div></td>" +
        //         "</tr>"); 

        //  $("#addActivityHeaderView").modal("hide");
        
        Swal.fire("Success", resp.mesg, "success");
        filterActivity();
        prevscreen();
    }  else if (resp.type == C_UPDATE) {
        // $("#confirmationMessageView").modal("hide");
        // $("#addActivityHeaderView").modal("hide");
        // showMessage('success', resp.mesg, "Success");
        // var draft = "<strong style=\"color:blue\">Draft</strong>";
        // var conf = "<strong style=\"color:green\">Confirm</strong>";

        // if (resp.data.status==0) {
        //     status=draft;
        //     var btn="<div><button title=\"View\" onclick=\"return showEditActivityHeader("+resp.data.id+",this);\" id=\"btnEdit\" class=\"btn btn-primary glyphicon glyphicon-edit btn-sm\"></button>" +
        //         "<button title=\"Delete\" onclick=\"javascript:popupDeleteActivity("+resp.data.id+", this);\" id=\"btnDelete\" data-toggle=\"modal\" class=\"btn btn-danger glyphicon glyphicon-trash btn-sm\"></button>"+
        //         "<button title=\"Print Preview\" onclick=\"javascript:showPrintActPreview("+resp.data.id+");\" id=\"btnPrintPreview\"  class=\"btn btn-default glyphicon glyphicon-print btn-sm\"></button>" +
        //         "<button title=\"Upload Additional Doc\" onclick=\"javascript:showActivityDocsView("+resp.data.id+");\" id=\"btnUploadAddDocSR\"  class=\"btn btn-info glyphicon glyphicon-file btn-sm\"></button>" +
        //         "</div>";
        // } else {
        //     status=conf;
        //     var btn="<div><button title=\"View\" onclick=\"return showEditActivityHeader("+resp.data.id+",this);\" id=\"btnEdit\" class=\"btn btn-primary glyphicon glyphicon-edit btn-sm\"></button>" +
        //         "<button title=\"Print Preview\" onclick=\"javascript:showPrintActPreview("+resp.data.id+");\" id=\"btnPrintPreview\"  class=\"btn btn-default glyphicon glyphicon-print btn-sm\"></button>" +
        //         "<button title=\"Upload Additional Doc\" onclick=\"javascript:showActivityDocsView("+resp.data.id+");\" id=\"btnUploadAddDocSR\"  class=\"btn btn-info glyphicon glyphicon-file btn-sm\"></button>" +
        //         "</div>";
        // }
        // 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>";

        //  var job_number     = $('#txtActivityJobNumber :selected').text().split("-");
        //  var customer_name  = $('#cobActivityCustomer :selected').text();
        //  $($(obj).closest('tr')).children('td:eq(1)').html(btnSigned) ;
        //  $($(obj).closest('tr')).children('td:eq(2)').text($('#txtActivityCode').val()) ;
        //  $($(obj).closest('tr')).children('td:eq(3)').text(job_number[0]) ;
        //  $($(obj).closest('tr')).children('td:eq(4)').text($('#txtActivityDate').val()) ;
        //  $($(obj).closest('tr')).children('td:eq(5)').text(customer_name) ;
        //  $($(obj).closest('tr')).children('td:eq(6)').text($('#txtActivityTitle').val()) ;
        //  $($(obj).closest('tr')).children('td:eq(7)').text($('#cobActivityDeduct :selected').text()) ;
        //  $($(obj).closest('tr')).children('td:eq(8)').html(status) ;
        //  $($(obj).closest('tr')).children('td:eq(9)').text($('#txtActivityUserName').val()) ;
        //  $($(obj).closest('tr')).children('td:eq(10)').html(btn) ;

        Swal.fire("Success", resp.mesg, "success");
        filterActivity();
        prevscreen();
    }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);

            $('#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').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);

            // $('#txtActivityDate').val(resp.data.headerData.date);
            // $('#cobActivityBu').val(resp.data.headerData.company_id);
            // $('#cobActivityType').val(resp.data.headerData.activity_type);

            // $('#txtActivityJobAssignment').html(resp.data.headerData.jobassign);
            // $('#cobActivityStatus').val(resp.data.headerData.status_project);
            // $('#txtActivityTask').val(resp.data.headerData.task_desc);

            // $('#txtTimeTrackerTotal').val(resp.data.headerData.tt_total);
            // $('#txtTimeTrackerTotalOverride').val(resp.data.headerData.tt_total_over);
            // $('#txtExpenseTrackerTotal').html(resp.data.headerData.et_total);

            // $('#cobActivityCustomer').val(resp.data.headerData.customer_id);
            //changeCustomer();
        
            // $('#cobActivityCustomerContact').html(resp.data.headerData.contact_opt);
            // $('#cobActivityCustomerContact').val(resp.data.headerData.contact_id);
            // $('#cobActivityLocation').html(resp.data.headerData.location_opt);
            // $('#cobActivityLocation').val(resp.data.headerData.location_id);


            // $('#cobActivityDeduct').val(resp.data.headerData.deduct);
           // changeDeduct();

           // if (resp.data.headerData.deduct==1) {
                // $('#formProject').show();
                // $('#cobActivityProject').html(resp.data.headerData.project_opt);
                // $('#cobActivityProject').val(resp.data.headerData.project_id);
           // }

            // $('#tbl-activity-time-tracker').html(resp.data.htmlItem);
            // $('#txtActivityJobAssignment').html(resp.data.jobassign.assignment);
            // $('#tbl-activity-expense-tracker').html(resp.data.htmlItemExp);

            var functionName = "updateActivityHeader(0)";

            var strBtn = "<button type=\"button\" class=\"btn btn-secondary\" onclick=\"prevscreen();\">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>";
            }

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

            // getChecklistActivity();
        } else {

            var functionName = "addActivityHeader(0)";
            $('#txtActivityUserName').val(resp.data.user_create);

           var strBtn = "<button type=\"button\" class=\"btn btn-secondary\" onclick=\"prevscreen();\">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) {
        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 == 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) ;
        $('#cobActivityCustPMName').val(resp.data.pmname) ;
        $('#txtActivityCustPMName').val($('#cobActivityCustPMName :selected').text()) ;

        $("#txtActivityTaskComb").html(resp.data.task);
    } else if (resp.type == C_GET + '_ASSIGNDETAIL') {
      $("#phase-activity"+resp.data.act_idx).val(resp.data.phase);
      $("#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);
      onOverrideToChange();

      // $("#checklistId").val(resp.data.checklist);
      // $("#txtTimeTrackerDesc").val(resp.data.desc);

      // if(resp.data.status == 0) {
      //   $("#btnCompleteTask").show();

      //   $('#btnCompleteTask').click(function() {
      //       showCompleteTaskModal(resp.data.id);
      //   });
      // } else {
      //   $("#btnCompleteTask").hide();
      // }

    }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');
    }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);

    } else if (resp.type == C_COMPLETE_TASK) {
        // showMessage('success', resp.mesg, "Success");
        // getAssignmentDetail();
    }else if (resp.type == "C_SHOW_UPLOAD_ATTACH_VIEW" ) {
        hideProgress(); 
        $("#uploadDocActivityView").modal("show");
        $('#modaluploadDocActivityContent').show().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 ++;
            }
            $("#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";

            console.log(url);
    showReport(url) ;
}


function mandatoryActivity(){
    var actTitle=$('#txtActivityTitle').val();
    
    if (!actTitle) {
        showMessage('error', "Service Title can't be blank", "Warning");
        $('#err_act_title').show();
        return false;
    }
    return true;

}

// function mandatoryConfirm(){
//     var code=$('#txtActivityCode').val();

//     if (!code) {
//         showMessage('error', "Service Code can't be blank", "Warning");
//         $('#err_act_code').show();
//         return false;
//     }
//     return true;

// }

// function mandatoryExpenseTracker(){
//     var finalAmount=$('#txtAddExFinalAmount').val();
//     var desc=$('#txtExpenseTrackerDesc').val();

//     if (finalAmount<=0.00) {
//         showMessage('error', "Expense Tracker Amount can't be 0.00", "Warning");
//         return false;
//     }if (!desc) {
//         showMessage('error', "Expense Tracker Description can't be blank", "Warning");
//         return false;
//     }
//     return true;
// 
// }

// function mandatoryTimeTracker(){
//     var desc=$('#txtTimeTrackerDesc').val();

//     if (!desc) {
//         showMessage('error', "Time Tracker Description can't be blank", "Warning");
//         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");
    // $('#txtActivityDate').prop("disabled", "disabled");
    // $('#cobActivityBu').prop("disabled", "disabled");
    // $('#cobActivityType').prop("disabled", "disabled");
    // $('#cobActivityStatus').prop("disabled", "disabled");
    // $('#txtActivityTask').prop("disabled", "disabled");
    // $('#txtTimeTrackerTotalOverride').prop("disabled", "disabled");
    // $('#cobActivityCustomer').prop("disabled", "disabled");
    // $('#cobActivityCustomerContact').prop("disabled", "disabled");
    // $('#cobActivityLocation').prop("disabled", "disabled");
    // $('#cobActivityDeduct').prop("disabled", "disabled");
    // $('#cobActivityProject').prop("disabled", "disabled");
    // $('#formTimeTracker').remove();
    // $('#formExpenseTracker').remove();
    // $('.btnPencil').remove();
    // $('.btnTrash').remove();

}

// function getChecklistActivity() {
 
//     var sep2        = "" ;
//     var id          = "" ;
//     var lines_id    =""; 
//     var checklist   = 0;   
    
//     $('#tbl-activity-time-tracker tbody tr').each(function() { 
      
//         checklist                   = $('.txtTcChecklist', this).html();
//         activity_line_id            = $(this).find("td").eq(0).html();
//         id                          = $(this).find("td").eq(1).html();
//         lines_id                    = lines_id + sep2 + id +'-'+checklist+'-'+activity_line_id;
//         sep2        =                "|" ;
     
//     }); 
    
//     var data = { 
//         "id"            : $('#txtActivityID').val(),
//         "lines_id"      : lines_id,
//         "type"          : "C_GET_CHECKLIST"
//         };
//     var url = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
//     callServer(url,"json",data,onActivityResponse,activity_obj) ;
// }

// function getChecklistVal() {
   
//     var sep2        = "" ;
//     var id          = "" ;
 
//     var lines_id    =""; 
//     var checklist   = 0;   
//     for (let index = 0; index < $("#countIndex").val(); index++) {
//         $('#tbl-activity-expense-checklist-body-'+index+' tr').each(function() { 
//             checklist               = ($('.inputCheck',this).is(':checked') ? '1' : '0');
//             remarks                 = $('.inputRemarks', this).val();
//             job_id                  = $(this).find("td").eq(1).html();
//             checklist_head_id       = $(this).find("td").eq(2).html();
//             checklist_detail_id     = $(this).find("td").eq(3).html();
//             activity_lines_id       = $(this).find("td").eq(4).html();
//             lines_id                = lines_id + sep2 + job_id+'-'+checklist_head_id+'-'+checklist_detail_id +'-'+checklist+'-'+remarks+'-'+activity_lines_id;
//             sep2                    = "|" ;
//         });
        
//     }
    
//     return lines_id;
// }

function sendEmailApproval() {
    $('#activityLoadingModal').modal('show');
    var data = { 
        "id"            : $('#txtActivityID').val(),
        "to_email"      : $('#activityEmailTo').val(),
        "cust_rep"      : $('#cobActivityCustomerContact :selected').text(),
        "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 showCompleteTaskModal(id) {
//     // $('#completeJobPlanTask').modal('show');  
//     var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
//                      "<button onclick=\"return completeTask(" + id + ", this);\" class=\"btn btn-danger\" > Complete </button>";
//     $('#modalcCnfirmationMessageButtonContent').html(strBtn);
//     $('#modalcompleteJobPlanTaskContent').html("Are you sure want to complete this task?");
//     $('#modalcompleteJobPlanTaskTitle').html("Complete Task");
//     $("#completeJobPlanTask").modal("show");
// }

// function completeTask(id) {
//     $("#completeJobPlanTask").modal("hide");
//     var data = { 
//             "id"            : id,
//             "type"          : C_COMPLETE_TASK
//             };
//     var url = "index.pzx?c=" + activity_url + "&d=" + new Date().getTime() ;
//     callServer(url,"json",data,onActivityResponse,activity_obj) ;
// }

function openEmailModal(id,custId) {
    var data = { 
        "id_activity"           : id,
        "id_customer"           : custId,
        "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"+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='glyphicon glyphicon-search' title='Preview' style='color:green; margin-top: 5px;' href='javascript:' onclick='downloadActivityeFile(\"" + docElements[4] +  "\", \"" + docElements[1] + "\")'>"+
                        "</a>&nbsp;&nbsp;&nbsp;<a class='glyphicon glyphicon-trash' title='Remove' style='color:red; margin-top: 5px;' href='javascript:' onclick='removeActivityeFile(" + docElements[3] + ")'></a>"+
                      "</td>" +
                      "<input type='hidden' name='lblIds' value='"+ docElements[3] +"'>" +
                      "</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",
                 "jobCentreId"  : $('#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 addActivityList() {
    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="onOverrideToChange('+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="-1">' + 
            '</td>' +

            '<td width="17%" class="kt-datatable__cell">' + 
                task + 
            '</td>' +

            '<td width="20%"  class="kt-datatable__cell">'+
                '<input type="text" class="col-lg-12 form-control txtActivityDesc" id="desc-activity'+activity_idx+'">'+
            '</td>'+

            '<td width="5%" class="kt-datatable__cell">' + 
                '<input type="text" class="col-lg-12 form-control txtActivityPhase" id="phase-activity'+activity_idx+'">' + 
            '</td>' +

            '<td width="8%" class="kt-datatable__cell">'+
                '<div class="input-group date">'+
                    '<input type="text" class="col-lg-12 form-control txtActivityStartDate" readonly placeholder="Select" id="startdate-activity' + activity_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 width="8%" class="kt-datatable__cell">'+
                '<div class="input-group date">'+
                    '<input type="text" class="col-lg-12 form-control txtActivityEndDate" readonly placeholder="Select" id="enddate-activity' + activity_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 width="7%" class="kt-datatable__cell">'+
                '<input class="col-lg-12 form-control txtActivityStartTime" id="starttime-activity'+activity_idx+'" placeholder="Select time" type="text" />'+
            '</td>' +

            '<td width="7%" class="kt-datatable__cell">' + 
                '<input class="col-lg-12 form-control txtActivityEndTime" id="endtime-activity'+activity_idx+'" placeholder="Select time" type="text" />'+
            '</td>' +

            '<td width="5%" class="kt-datatable__cell">'+
                '<input type="text" class="col-lg-12 form-control txtActivityHours" id="hours-activity'+activity_idx+'">' + 
            '</td>' +

            '<td width="5%" class="kt-datatable__cell">'+
                breakActivity+ 
            '</td>'+

            '<td width="8%" class="kt-datatable__cell">'+
                '<input type="text" class="col-lg-12 form-control txtActivityAftBreak" id="aftbreak-activity'+activity_idx+'" value="0">' + 
            '</td>'+

            '<td width="8%" class="kt-datatable__cell">'+
                '<input type="text" class="col-lg-12 form-control txtActivityOverride" id="override-activity'+activity_idx+'">' + 
            '</td>'+
            
            '<td width="9%"  class=\"kt-datatable__cell\" style="width:40px;">'+
                '<button title="Delete" onclick="javascript: deleteActivityList('+activity_idx+', this);" id="btnDelete" class="btn btn-danger btn-sm btn-icon btn-icon-md ml-2"><i class="fa fa-trash"></button>'+
            '</td>'+
        '</tr>'
    ); 

    calculateTcMinute();

    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>'
        }
    }

    $(".txtActivityStartDate").datepicker(dteopt) ;
    // $('.txtActivityStartDate').on('changeDate', function(ev){
    //     set(activity_idx);
    //     onOverrideToChange(activity_idx);

    // });

    $(".txtActivityEndDate").datepicker(dteopt) ;
    // $('.txtActivityEndDate').on('changeDate', function(ev){
    //     set(activity_idx);
    //     onOverrideToChange(activity_idx);

    // });

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

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

function set(act_idx) {
    //Calculate Hour
    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);
    
    alert(startTime);
    alert(endTime);
    alert(Hour);
    if (Hour<0) {
        Swal.fire('error', "Time not valid, End Time must more than Start Time.", "Error");
        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) {
        Swal.fire('error', "Date not valid, End Date must more than Start Date.", "Error");
        return false;
    }

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

    alert(fHour);
    $('#hours-activity'+act_idx).val(fHour);
    $('#aftbreak-activity'+act_idx).val(parseFloat(AftBreak).toFixed(2));

    AftBreak = fHour-Break;

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

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

function getTimeTrackerBreakUpdate(Days){
    return parseFloat($('.txtActivityBreak').val() * (Days + 1)/60).toFixed(2);
}

function calculateTcMinute(){
    var totalHour=0;
    var totalOverride = 0;
   $('#activity-list-table tbody tr').each(function() {
               var Hour=parseFloat($('.txtActivityAftBreak', this).html());
               if(!Hour){Hour = 0;}
               totalHour += Hour;        
               
               var Override=parseFloat($('.txtActivityOverride', this).html());
               if(!Override){Override = 0;}
               totalOverride += Override;       
            });
            
   $('#txtTimeTrackerTotal').html(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);

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

    $('#override-activity'+act_idx).val(detailOverride);
}


function deleteActivityList(idx) {
    $('#trActivityList'+idx).remove() ;
    calculateTcMinute();
}