var C_PROJECT_FILTER                    = "516";
var C_ADD_PROJECT_VIEW                  = "517";
var C_UPDATE_PROJECT_VIEW               = "518";
var C_DELETE_PROJECT                    = "519";
var C_REPORT_UTILIZATION                = "521";
var C_REPORT_UTILIZATION_PRINT          = "522";


var project_obj                         = null;
var m_project_invoice_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 showProjectReportUtilization(id){
    var data = { "type": C_REPORT_UTILIZATION, 
                    'id': id
                    };
    var url  = "index.pzx?c=" + project_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onProjectResponse,null) ;
}

function decimalNumber(){
    var tt_over = $('#txtTimeTrackerTotalOverride').val();
    $('#txtTimeTrackerTotalOverride').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 filterProject(){
    var data = { "type": C_PROJECT_FILTER, 
                        'title': $("#filterTitleProject").val(),
                        'cust': $("#filterCustomerProject").val(),
                        "status": 'all'
                    };
    var url  = "index.pzx?c=" + project_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onProjectResponse,null) ;
}


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


function addProject() {
    saveProject(C_ADD);
}

function updateProject() {
    saveProject(C_UPDATE) ; 
}


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 saveProject(type){
    if (validateProject()){
        var data = {        "type"              : type,
                            "id"                : $('#txtProjectID').val(),
                            "code"              : $('#txtProjectCode').val(),
                            "title"             : $('#txtProjectTitle').val(), 
                            "desc"              : $('#txtProjectDesc').val(),
                            "cust"              : $('#cmbProjectCustomer').val(),
                            "total_mandays"     : $('#txtProjectTotalMandays').val(),
                            "active"            : ($('#chkProjectActive').is(':checked') ? '1' : '0'),
                            "invoice"           : getProjectInvoice()

                        };
        var url  = "index.pzx?c=" + project_url + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onProjectResponse,project_obj) ;
    } 
}


function showEditProject(id, obj) {
    project_obj = obj ;
    showProgress("loading Project" ) ;
    var data  = { "type": C_UPDATE_PROJECT_VIEW, "id" : id} ;
    var url   = "index.pzx?c=" + project_url + "&t=" + C_UPDATE_PROJECT_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onProjectResponse,null) ;
}

function popupDeleteProject(id, obj){
    var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                     "<button onclick=\"return deleteProject(" + id + ", this);\" class=\"btn btn-danger\" > Delete </button>";
    $('#modalDeleteProjectConfirmationButton').html(strBtn);
    $('#modalDeleteProjectConfirmationContent').html("Are you sure you want to delete this project?");
    $('#modalDeleteProjectConfirmationTitle').html("Delete Project");
    $("#deleteProjectConfirmationView").modal("show");
}

function deleteProject(id, obj) {
    $("#deleteProjectConfirmationView").modal("hide");
    var data = { 
            "id"            : id,
            "type"          : C_DELETE_PROJECT
            };
    var url = "index.pzx?c=" + project_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onProjectResponse,obj) ;
}
//`Service



function onProjectResponse(obj,resp){
	$('#activityLoadingModal').modal('hide');
    if (resp.status != C_OK ) {
        showMessage('error', resp.mesg, "Warning");
        return false;
    }

    if (resp.type == C_ADD) {
        showMessage('success', resp.mesg, "Success");

        $('#project-table tbody:first tr:first').after(
                "<tr id='project-rows-" + resp.data.id + "'>" + 
                "<td style='display:none'>" + resp.data.id + "</td>" + 
                "<td>" + resp.data.code + "</td>" +
                "<td>" + resp.data.title + "</td>" +
                "<td>" + resp.data.cust + "</td>" +
                "<td>" + resp.data.status + "</td>" + 
                "<td>" + resp.data.bill + "</td>" + 
                "<td><div><button  title=\"View\" onclick=\"return showEditProject('" + resp.data.id + "', this);\" id='btnEdit' data-toggle='modal' class='btn btn-primary glyphicon glyphicon-edit btn-sm'></button>" +
                "<button  title=\"Delete\" onclick=\"return popupDeleteProject('" + resp.data.id + "', this);\" id='btnDelete' data-toggle='modal' class='btn btn-danger glyphicon glyphicon-trash btn-sm'></button>" +
                "<button  title=\"Print Preview\" onclick=\"return showProjectReportUtilization('" + resp.data.id + "');\" id='btnPrintPreview' data-toggle='modal' class='btn btn-danger glyphicon glyphicon-print btn-sm'></button>" +
                "</div></td>" +
                "</tr>"); 

         $("#addCustomerView").modal("hide");
    }  else if (resp.type == C_UPDATE) {
         $("#addProjectView").modal("hide");
        showMessage('success', resp.mesg, "Success");

        $($(obj).closest('tr')).children('td:eq(1)').text(resp.data.code) ;
        $($(obj).closest('tr')).children('td:eq(2)').text(resp.data.title) ;
        $($(obj).closest('tr')).children('td:eq(3)').text(resp.data.cust) ;
        $($(obj).closest('tr')).children('td:eq(4)').text(resp.data.status) ;
        $($(obj).closest('tr')).children('td:eq(5)').text(resp.data.bill) ;
    }else if (resp.type == C_DELETE_PROJECT) {
        showMessage('success', resp.mesg, "Success");
        $('#project-rows-'+resp.data).remove() ;
    }else if (resp.type == C_ADD_PROJECT_VIEW || resp.type == C_UPDATE_PROJECT_VIEW) {
        $("#addProjectView").modal("show");
        $('#modalAddProjectHeaderViewContent').show().html(resp.data.all);
        m_project_invoice_idx = 0 ;

       if (resp.type == C_UPDATE_PROJECT_VIEW) {
	
            $('#txtProjectID').val(resp.data.headerData.id) ;
            $('#txtProjectCode').val(resp.data.headerData.code) ;
            $('#txtProjectTitle').val(resp.data.headerData.title) ;
            $('#txtProjectDesc').val(resp.data.headerData.desc) ;
            $('#cmbProjectCustomer').val(resp.data.headerData.cust) ;
            $('#txtProjectTotalMandays').val(resp.data.headerData.total_mandays) ;
            
            if(resp.data.headerData.status == '1'){
                $('#chkProjectActive').prop('checked', true);
            } else {
                $('#chkProjectActive').prop('checked', false);
            }

            var functionName = "updateProject()";
            
            showProjectInvoice(resp.data.headerData.project_invoices);

            var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                        "<button id=\"btnProjectAdd\" class=\"btn btn-primary\" onclick=\"return "+functionName+";\">Save</button>";

            $('#modalAddProjectHeaderViewButtonContent').show().html(strBtn);
        } else {
            $('#txtProjectTotalMandays').val("0.00") ;
            clearProjectInvoice();
            
            var functionName = "addProject()";

            var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                        "<button id=\"btnProjectAdd\" class=\"btn btn-primary\" onclick=\"return "+functionName+";\">Save</button>";

       		$('#modalAddProjectHeaderViewButtonContent').show().html(strBtn); 
        }
    }else if(resp.type == C_PROJECT_FILTER) {
        $('#project-table').html('');
        $('#project-table').append(resp.data);
    }else if(resp.type == C_REPORT_UTILIZATION){
        $("#projectReportUtilizationView").modal("show");
        $('#modalProjectReportUtilizationViewContent').show().html(resp.data.all);
        var strBtn = "<button id=\"btnProjectReportUtilizationPrint\" class=\"btn btn-default glyphicon glyphicon-print btn-sm\" style=\"float:left\" onclick=\"javascript:showPrintProjectUtilPreview("+resp.data.id+");\" title=\"Print Preview\"></button>"+
                    "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>";
        $('#modalProjectReportUtilizationFooter').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 validateProject(){
    
    if ($('#txtProjectCode').blank()) {
        showMessage('error', "Project Code cannot be blank", "Warning");
        return false;
    }
    if ($('#txtProjectTitle').blank()) {
        showMessage('error', "Project Title cannot be blank", "Warning");
        return false;
    }
    return true;
}


function showProjectInvoice(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_project_invoice_idx++;
			$('#project-invoice-table').append("<tr id='trProjectInvoice" + m_project_invoice_idx + "'><td style='width:30px;display:none'>" +m_project_invoice_idx+ "</td>" +
                                    "<td style='width:30%;'><input type='text' class='form-control' id='txtProjectInvoiceNo-" + m_project_invoice_idx + "' value='" + fld[0] + "'/></td>" +
                                    "<td style='width:30%;'><input type='text' style='text-align:right' class='form-control' id='txtProjectInvoiceBilled-" + m_project_invoice_idx + "' value='" + fld[1] + "'/></td>" +
                                    "<td style='width:30%;'><input type='text' style='text-align:right' class='form-control' id='txtProjectInvoicePaid-" + m_project_invoice_idx + "' value='" + fld[2] + "'/></td>" +
                                    "<td style='text-align:center;'><a href='javascript:' onclick='removeProjectInvoice(" + m_project_invoice_idx + ")'><span class='glyphicon glyphicon-trash'></span></a></a></td></tr>"); 
			
		}
	}
}

function addProjectInvoice() {
    if($('#txtProjectInvoiceNo').blank() || $('#txtProjectInvoiceBilled').blank() || $('#txtProjectInvoicePaid').blank()){
        showMessage('error', "Please fill in the invoice information!", "Warning");
        return false;
    }
	m_project_invoice_idx++;
	$('#project-invoice-table').append("<tr id='trProjectInvoice" + m_project_invoice_idx + "'><td style='width:30px;display:none'>" +m_project_invoice_idx+ "</td>" +
		"<td style='width:30%;'><input type='text' class='form-control' id='txtProjectInvoiceNo-" + m_project_invoice_idx + "' value='" + $('#txtProjectInvoiceNo').val() + "'/></td>" +
		"<td style='width:30%;'><input type='text' style='text-align:right' class='form-control' id='txtProjectInvoiceBilled-" + m_project_invoice_idx + "' value='" + $('#txtProjectInvoiceBilled').val() + "'/></td>" +
		"<td style='width:30%;'><input type='text' style='text-align:right' class='form-control' id='txtProjectInvoicePaid-" + m_project_invoice_idx + "' value='" + $('#txtProjectInvoicePaid').val() + "'/></td>" +
		"<td style='text-align:center;'><a href='javascript:' onclick='removeProjectInvoice(" + m_project_invoice_idx + ")'><span class='glyphicon glyphicon-trash'></span></a></td></tr>"); 
	clearProjectInvoice();
}
function clearProjectInvoice() {
	$('#txtProjectInvoiceNo').val('') ;
	$('#txtProjectInvoiceBilled').val('0.00') ;
	$('#txtProjectInvoicePaid').val('0.00') ;
}
function removeProjectInvoice(idx) {
	$('#trProjectInvoice'+idx).remove() ;
}

function getProjectInvoice(){
    
	var lines = "" ;
	var sep = "" ;
	$('#project-invoice-table tr').each(function() { 
        id = $(this).find("td").eq(0).html();
        
		invoice_no = $('#txtProjectInvoiceNo-' + id).val();
		invoice_billed = $('#txtProjectInvoiceBilled-' + id).val();
		invoice_paid = $('#txtProjectInvoicePaid-' + id).val();
        
        lines = lines + sep + invoice_no  + "~" + invoice_billed + "~" + invoice_paid;
        sep = "|" ;
	}); 
	return lines ;
}


function showPrintProjectUtilPreview(id){
    var url = "index.pzx?c=" + project_url + "&id=" + id +
            "&t=" + C_REPORT_UTILIZATION_PRINT + "&r=1";
    showReport(url) ;
}