var C_PLAN_FILTER                       = "201";
var C_ADD_PLAN_VIEW                     = "202";
var C_GENERATE_PLAN_SCHEDULE            = "203";
var C_GET_PLAN_USER_DETAIL              = "204";
var C_UPDATE_PLAN_VIEW                  = "205";
var C_DELETE_PROJECT                    = "519";
var C_REPORT_UTILIZATION                = "521";
var C_REPORT_UTILIZATION_PRINT          = "522";


var project_obj                         = null;
var m_participant_idx               = 0;


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 addParticipantItem() {
    m_participant_idx++;
    $('#project-participant-table').append("<tr id='trParticipant" + m_participant_idx + "'><td style='width:30px;display:none'>" +m_participant_idx+ "</td>" +
        "<td style='width:30%;display:none;' id='cmbPtcType-" + m_participant_idx + "'>"+$('#cmbPtcType').val()+"</td>" +
        "<td style='width:30%;display:none;' id='cmbPtcUserId-" + m_participant_idx + "'>"+$('#cmbPtcUserId').val()+"</td>" +
        "<td style='width:30%;'>"+$('#cmbPtcType :selected').text()+"</td>" +
        "<td style='width:10%;'>" + $('#cmbPtcUserId :selected').text() + "</td>" +
        "<td style='width:20%;' id='cmbPtcName-" + m_participant_idx + "'>" + $('#cmbPtcName').val() + "</td>" +
        "<td style='width:20%;' id='cmbPtcEmail-" + m_participant_idx + "'>" + $('#cmbPtcEmail').val() + "</td>" +
        "<td style='text-align:center;'><a href='javascript:' onclick='removeParticipant(" + m_participant_idx + ")'><span class='glyphicon glyphicon-trash'></span></a></td></tr>"); 
    clearParticipant();
}

function removeParticipant(idx) {
    $('#trParticipant'+idx).remove() ;
}

function removePlanSchedule(idx) {
    $('#trSchedule'+idx).remove() ;
}

function clearParticipant() {
    $('#cmbPtcType').val('0');
    $('#cmbPtcUserId').val('0');
    getUserDetail();
}

function filterPlan(){
    var data = { "type": C_PLAN_FILTER, 
                 //"status": $('#plan_filter_header').val()
                 "status": "all"
                };
    var url  = "index.pzx?c=" + plan_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onPlanResponse,null) ;
}

function showAddPlan(){
    showProgress("loading Project" ) ;
    var data = { "type": C_ADD_PLAN_VIEW} ;
    var url  = "index.pzx?c=" + plan_url + "&t=" + C_ADD_PLAN_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onPlanResponse,null) ;
}

function generateSchedule() {
    var data = { "type": C_GENERATE_PLAN_SCHEDULE,"schedule_type":$('#cmbPlanSchedule').val(),"id_plan":$('#txtPlanID').val()} ;
    var url  = "index.pzx?c=" + plan_url + "&t=" + C_GENERATE_PLAN_SCHEDULE  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onPlanResponse,null) ;
}

function ChangeScheduleType() {
    var type = $('#cmbPlanSchedule').val();

    if(type==0) {
        $('#fgPlanSchedule').hide();
    } else {
         $('#fgPlanSchedule').show();
    }
}

function getUserDetail() {
    if ($('#cmbPtcUserId').val() != "0") {
        var data = { "type": C_GET_PLAN_USER_DETAIL,"user_id":$('#cmbPtcUserId').val()} ;
        var url  = "index.pzx?c=" + plan_url + "&t=" + C_GET_PLAN_USER_DETAIL  + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onPlanResponse,null) ;
    }else{
        $('#cmbPtcName').prop('disabled','');
        $('#cmbPtcEmail').prop('disabled','');
        $('#cmbPtcName').val("");
        $('#cmbPtcEmail').val("");
    }
}

function showPlan() {
    if (validatePlan()){
        var data = {        "type"              : "SHOW_PLAN",
                            "id"                : $('#txtPlanID').val(),
                            "jobnumber"         : $('#cmbPlanJobNumber').val(),
                            "jobnumberval"      : $('#cmbPlanJobNumber :selected').text(),
                            "desc"              : $('#txtPlanDesc').val(),
                            "schedule_type"     : $('#cmbPlanSchedule').val(), 
                            "start_date"        : $('#txtPlanStart').val(),
                            "end_date"          : $('#txtPlanEnd').val(),
                            "time"              : $('#txtPlanTime').val(),
                            "is_update"         : $('#txtIsUpdate').val(),
                            "schedule"          : getSchedule(),
                            "participant"       : getParticipant()
                        };
        var url  = "index.pzx?c=" + plan_url + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onPlanResponse,null) ;
    }
    
}

function addPlan() {
    savePlan(C_ADD);
}

function updatePlan() {
    savePlan(C_UPDATE) ; 
}

function savePlan(type){
    if (validatePlan()){
        var data = {        "type"              : type,
                            "id"                : $('#txtPlanID').val(),
                            "jobnumber"         : $('#cmbPlanJobNumber').val(),
                            "desc"              : $('#txtPlanDesc').val(),
                            "schedule_type"     : $('#cmbPlanSchedule').val(), 
                            "start_date"        : $('#txtPlanStart').val(),
                            "end_date"          : $('#txtPlanEnd').val(),
                            "time"              : $('#txtPlanTime').val(),
                            "schedule"          : getSchedule(),
                            "planschedule"      : getPlanSchedule(),
                            "participant"       : getParticipant()
                        };
        var url  = "index.pzx?c=" + plan_url + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onPlanResponse,null) ;
    } 
}


function validatePlan(){
    if ($('#txtPlanDesc').blank()) {
        showMessage('error', "Plan Desc cannot be blank", "Warning");
        return false;
    }
    return true;
}

function getSchedule(){
    var count = $('#txtSchedulePlanCount').val();
    var lines = "" ;
    var sp = "" ;

    for (var i = 1; i <= count; i++) {
        if ($('#cbkSchedule-' + i).is(':checked')) {
            chk_val    = $('#cbkSchedule-' + i).val();
            lines += sp + chk_val;
            sp = "~" ;
        }
    }
    return lines ;
}

function getPlanSchedule(){
    var count = $('#generatedPLanCount').val();
    var lines = "" ;
    var sp = "" ;

    for (var i = 0; i < count; i++) {
       
        var date = $('#txtDate'+i).val();
        var time = $('#txtPlanTime'+i).val();
        lines += sp + date + "|" + time;
        sp = "~" ;
        
    }
    return lines ;
}

function getParticipant(){
    var lines = "" ;
    var sep = "" ;
    $('#project-participant-table tr').each(function() { 
        idx     = $(this).find("td").eq(0).html();
        type    = $('#cmbPtcType-' + idx).html();
        user_id = $('#cmbPtcUserId-' + idx).html();
        name    = $('#cmbPtcName-' + idx).html();
        email   = $('#cmbPtcEmail-' + idx).html();
        
        lines += sep + idx  +"~"+ type +"~"+ user_id +"~"+name+"~"+email;
        sep = "|" ;
    }); 
    return lines ;
}

function popupDeletePlan(id, obj){
    var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                     "<button onclick=\"return deletePlan(" + id + ", this);\" class=\"btn btn-danger\" > Delete </button>";
    $('#modalDeletePlanConfirmationButton').html(strBtn);
    $('#modalDeletePlanConfirmationContent').html("Are you sure you want to delete this plan?");
    $('#modalDeletePlanConfirmationTitle').html("Delete Plan");
    $("#deletePlanConfirmationView").modal("show");
}

function deletePlan(id, obj) {
    var data = { 
            "id"            : id,
            "type"          : C_DELETE
            };
    var url = "index.pzx?c=" + plan_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onPlanResponse,obj) ;
}



function showEditPlan(id, obj) {
    showProgress("loading Project" ) ;
    var data  = { "type": C_UPDATE_PLAN_VIEW, "id" : id} ;
    var url   = "index.pzx?c=" + plan_url + "&t=" + C_UPDATE_PLAN_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onPlanResponse,null) ;
}


function onPlanResponse(obj,resp){
    $('#planLoadingModal').modal('hide');
    if (resp.status != C_OK ) {
        showMessage('error', resp.mesg, "Warning");
        return false;
    }
    
    if(resp.type == C_PLAN_FILTER) {
        $('#plan-table').html('');
        $('#plan-table').append(resp.data);
    }else if (resp.type == C_ADD_PLAN_VIEW || resp.type == C_UPDATE_PLAN_VIEW) {
        $("#addPlanView").modal("show");
        $('#modalAddPlanContent').html(resp.data.all);
        //var functionName = "addPlan()";
        var functionName = "showPlan()";
       if (resp.type == C_UPDATE_PLAN_VIEW) {
    
            $('#txtPlanID').val(resp.data.headerData.id) ;
            $('#txtPlanDesc').val(resp.data.headerData.desc) ;
            $('#cmbPlanJobNumber').val(resp.data.headerData.jobnumber) ;
            $('#cmbPlanSchedule').val(resp.data.headerData.schedule_type) ;
            $('#txtPlanStart').val(resp.data.headerData.start_time) ;
            $('#txtPlanEnd').val(resp.data.headerData.end_time) ;
            $('#txtPlanTime').val(resp.data.headerData.time) ;
            $('#txtIsUpdate').val('update');
            showPlanParticipant(resp.data.headerData.participant);
            //functionName = "updatePlan()";
        }
        var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                        "<button id=\"btnPlanAdd\" class=\"btn btn-primary\" onclick=\"return "+functionName+";\">Show Plan</button>";

        $('#modalAddPlanFooter').show().html(strBtn); 
        generateSchedule();
    }else if(resp.type == C_GENERATE_PLAN_SCHEDULE){
        $('#fgPlanSchedule').html(resp.data.schedule);
        $('#txtSchedulePlanCount').val(resp.data.count);
        //Schedule
        var scd = resp.data.schedule_val;
        if (scd!=0) {
            var arr_scd = scd.split('~');
            for (var i = 0; i < arr_scd.length; i++) {
                $('#cbkSchedule-' + arr_scd[i]).prop('checked', true);
            }
        }
        //========
    }else if(resp.type == C_GET_PLAN_USER_DETAIL){
            $('#cmbPtcName').val(resp.data.name);
            $('#cmbPtcEmail').val(resp.data.email);
            $('#cmbPtcName').prop('disabled','disabled');
            $('#cmbPtcEmail').prop('disabled','disabled');
    }else if (resp.type == C_ADD) {
        showMessage('success', resp.mesg, "Success");
        $("#addPlanView").modal("hide");
        $("#showPlanView").modal("hide");
        filterPlan();
    }else if (resp.type == C_DELETE) {
        $("#deletePlanConfirmationView").modal("hide");
        filterPlan();
    }else if (resp.type == C_UPDATE) {
        showMessage('success', resp.mesg, "Success");
        $("#addPlanView").modal("hide");
        $("#showPlanView").modal("hide");
        filterPlan();
    }else if (resp.type =="SHOW_PLAN"){
        if(resp.data.is_update == 'update'){
            var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
            "<button onclick=\"return updatePlan();\" class=\"btn btn-success\" > Save & Generate </button>";
        }else{
            var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                     "<button onclick=\"return addPlan();\" class=\"btn btn-success\" > Save & Generate </button>";
        }
        
        $('#modalShowPlanViewTitle').html("Plan Preview");
        $('#modalShowPlanViewContent').html(resp.data.htmlContent);
        $('#modalShowPlanButtonContent').html(strBtn);
        $("#showPlanView").modal("show");
        $('#generatedPLanCount').val(resp.data.countIndex);
        for (var i = 0 ; i < resp.data.countIndex ; i++) {
            $('#txtDate'+i).datepicker({
                format: "dd/mm/yyyy"
            });
            $('#txtDate'+i).on('changeDate', function(ev){
                $(this).datepicker('hide');
            });
        
            $('#txtPlanTime'+i).timepicker({
                minuteStep:1
            });
        }
    }else if (resp.type == "C_JOB_DETAIL_VIEW") {
        $('#jobDetailView').modal('show');
        $('#jobDetailViewViewContent').html(resp.data.htmlContent);
        
        $('#txtCentreCoyName').val(resp.data.coyname);
        $('#cobCentreCustCode').val(resp.data.cust);
        $('#cobCentreLocCode').val(resp.data.loc);
        $('#txtCentreLocContactName').val(resp.data.contactname);
        $('#txtCentreLocContactPhone').val(resp.data.contactphone);
        $('#txtCentreLocContactEmail').val(resp.data.contactemail);
        $('#txtCentreLocContactAddress').val(resp.data.address);
        $('#txtCentreJobNumber').val(resp.data.jobnumber);
        $('#txtCentreJobType').val(resp.data.jobtype);
        $('#txtCentreJobName').val(resp.data.jobname);
        $('#txtCentreJobConfirmDate').val(resp.data.jobconfirmdate);
        $('#txtCentreJobStartDate').val(resp.data.jobstartdate);
        $('#txtCentreTotalMandays').val(resp.data.totalmandays);
        $('#planEquipmentData-body').html(resp.data.jobcentre_list_equipment);

    }
}

function showPlanParticipant(lines) {
    if (lines == undefined || lines == null || lines == "") return ;
    
    var line = lines.split('|') ;
    var fld = "" ;
    for (var i = 0 ; i < line.length ; i++) {
        if (line[i] != "") {
            fld = line[i].split('~') ;
            m_participant_idx++;
            $('#project-participant-table').append("<tr id='trParticipant" + m_participant_idx + "'><td style='width:30px;display:none'>" +m_participant_idx+ "</td>" +
            "<td style='width:30%;display:none;' id='cmbPtcType-" + m_participant_idx + "'>"+fld[1]+"</td>" +
            "<td style='width:30%;display:none;' id='cmbPtcUserId-" + m_participant_idx + "'>"+fld[2]+"</td>" +
            "<td style='width:30%;'>"+getTypePlan(fld[1])+"</td>" +
            "<td style='width:10%;'>" + fld[5] + "</td>" +
            "<td style='width:20%;' id='cmbPtcName-" + m_participant_idx + "'>" + fld[3] + "</td>" +
            "<td style='width:20%;' id='cmbPtcEmail-" + m_participant_idx + "'>" + fld[4] + "</td>" +
            "<td style='text-align:center;'><a href='javascript:' onclick='removeParticipant(" + m_participant_idx + ")'><span class='glyphicon glyphicon-trash'></span></a></td></tr>"); 
            
        }
    }
}

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 getTypePlan(id) {
    var val ="";
    if (id==0) {
        val = "Assign";
    }else if(id==1){
        val = "Done";
    }else if(id==2){
        val = "Not Done";
    }else{
        val = "";
    }

    return val;
}

function showJobDetail() {
    var data  = { "type": "C_JOB_DETAIL_VIEW", "id" : $('#cmbPlanJobNumber').val()} ;
    var url   = "index.pzx?c=" + plan_url + "&t=" +"C_JOB_DETAIL_VIEW"  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onPlanResponse,null) ;
}