var C_SALES_QUOTATION_FILTER                        = "3001";
var C_SALES_QUOTATION_ADD_VIEW                      = "3002";
var C_SALES_QUOTATION_ADD                           = "3003";
var C_SALES_QUOTATION_PRINT_PREVIEW                 = "3004";
var C_SALES_QUOTATION_UPDATE_VIEW                   = "3005";
var C_SALES_QUOTATION_UPDATE                        = "3006";
var C_SALES_QUOTATION_DELETE                        = "3007";
var C_ADD_UPLOAD_ATTACH_SALES_QUOT_VIEW             = "3008";
var C_ADD_UPLOAD_ATTACH_SALES_QUOT_DOC              = "3009";
var C_SAVE_ATTACHMENT                               = "3010";
var C_DOWNLOAD_ATTACHMENT                           = "3011";
var C_DELETE_ATTACHMENT                             = "3012";
var C_ADD_UPLOAD_ATTACH_SALES_QUOT_REVISE_VIEW      = "3013";
var C_SALES_QUOTATION_COPY                          = "3014";
var C_SALES_QUOTATION_REVISE_LIST                   = "3015";
var C_SALES_QUOTATION_REVISE_UPDATE                 = "3016";
var C_SALES_QUOTATION_CLOSED                        = "3017";
var C_SALES_QUOTATION_APPROVAL_FILTER               = "3019";
var C_SALES_QUOTATION_APPROVAL_VIEW                 = "3020";
var C_SALES_QUOTATION_APPROVAL_CONFIRM              = "3021";
var C_SALES_QUOTATION_UPDATE_EXPECTED               = "3022";

var sales_quotation_obj   = null;
var sales_quotation_idx   = 1;
var sales_item_idx = 1;
var sales_item_counter = 0;
var sales_item_additional_counter = 0;
var sales_item_section_idx = 0;
var sales_apdx_idx = 0;
var sales_projectplan_idx = 0;
var sales_ms_idx = 0;
var sales_cover_idx = 1;

var img_idx      = 0;

$(document).ready(function () {    
    // $('#div-buttons :input').attr("disabled", true);
    $('#general :input').attr("disabled", true);
    $('#items :input').attr("disabled", true);
    $('#mands :input').attr("disabled", true);
    $('#projectplan :input').attr("disabled", true);
    $('#cover :input').attr("disabled", true);
    $('#footer :input').attr("disabled", true);
    $('#appendix :input').attr("disabled", true);
    $('#attachment :input').attr("disabled", true);
    $('#btnPreviewSalesQuotation').prop("disabled", true);
    $('#btnSubmitSalesQuotation').prop('disabled',true);
    $('#btnIssueSalesQuotation').prop('disabled',true);
    $('#btnReviseSalesQuotation').prop('disabled',true);
    $('#btnAcceptSalesQuotation').prop('disabled',true);
    $('#btnClosedSalesQuotation').prop('disabled',true);
    $('#btnApprovalSalesQuotation').prop('disabled',true);
    checkMonth();
});

function checkMonth() {
    var today = new Date();
    var d = today.getDate();
    // console.log(d);

    // if(d == "1") {
        var data  = { "type": "RESET_QUOTATION_RN" } ;
        var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + "RESET_QUOTATION_RN"  + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onSalesQuotationResponse,null) ;
    // }
}

function onCheckChanged(obj, txtid) {
    // alert($(obj).is(":checked"));
    if($(obj).is(":checked")) {
        $('#'+txtid).prop('disabled', '');
    } else {
        $('#'+txtid).val('');
        $('#'+txtid).prop('disabled', 'disabled');
    }
}

function changeCurrencyDetail() {
    currency = $('#cobSalesQuotationCurrency :selected').text();
    $('#lblSalesProjectPlanCurr').text(currency);
    $('#lblSalesMaintenanceCurr').text(currency);
}
function deleteSalesQuotation(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) {
            sales_quotation_obj = obj ;
            var data  = { "type": C_SALES_QUOTATION_DELETE, "id" : id } ;
            var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + C_SALES_QUOTATION_DELETE  + "&d=" + new Date().getTime() ;
            callServer(url,"json",data,onSalesQuotationResponse,null) ;
        }
    });
}
function showAddSalesQuotation() {    
    screen_index = 0;
    var data  = { "type": C_SALES_QUOTATION_ADD_VIEW, "index":screen_index } ;
    var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + C_SALES_QUOTATION_ADD_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}
function showEditSalesQuotation(id, revise_type, obj) {
    sales_quotation_obj = obj ;
    // screen_index = 0;
    var data  = { "type": C_SALES_QUOTATION_UPDATE_VIEW, "id" : id, "revise_type": revise_type, "index":screen_index } ;
    var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + C_SALES_QUOTATION_UPDATE_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}
function printPreviewSalesQuotationPDF(id) {    
    if(id == undefined) {
        id = $('#txtSalesQuotationID').val();
    }

    var url = "index.pzx?c=" + sales_quotation_url + "&id=" + id + "&t=" + C_SALES_QUOTATION_PRINT_PREVIEW + "&r=1";
	showReport(url) ;
}
function previewSalesQuotationPDF(id) {
    var select = printSelection();
    
    if(select.length == 0) {
        Swal.fire("System Warning", "Please select content to print.", "warning");
        return select;
    }
    
    if(id == undefined) {
        id = $('#txtSalesQuotationID').val();
    }

    var url = "index.pzx?c=" + sales_quotation_url + "&id=" + id + "&t=" + C_SALES_QUOTATION_PRINT_PREVIEW + "&r=1&s=" + JSON.stringify(select);
	showReport(url) ;
}
function printSelection() {
    var select = [];

    if($('#chkSelectIssue').is(':checked')) {
        data = {"select" : "issue", "sequence" : $('#txtPageIssue').val()};
        select.push(data);
    }
    if($('#chkSelectItems').is(':checked')) {
        data = {"select" : "items", "sequence" : $('#txtPageItems').val()};
        select.push(data);
    }
    if($('#chkSelectMS').is(':checked')) {
        data = {"select" : "maintenance", "sequence" : $('#txtPageMS').val()};
        select.push(data);
    }
    if($('#chkSelectProject').is(':checked')) {
        data = {"select" : "project", "sequence" : $('#txtPageProject').val()};
        select.push(data);
    }
    if($('#chkSelectCover').is(':checked')) {
        data = {"select" : "cover", "sequence" : $('#txtPageCover').val()}; 
        select.push(data);
    }
    if($('#chkSelectFooter').is(':checked')) {
        data = {"select" : "footer", "sequence" : $('#txtPageFooter').val()}; 
        select.push(data);
    }
    if($('#chkSelectAppendix').is(':checked')) {
        data = {"select" : "appendix", "sequence" : $('#txtPageAppendix').val()};
        select.push(data);
    }

    return select;
}
function filterSalesQuotation(){
    showProgress("Loading Sales Quotation" ) ;
    
    var data = { 
        "type"          : C_SALES_QUOTATION_FILTER, 
        "coy_id"        : $('#cmbSalesQuotationCoyFilter').val(), 
        "prospect"      : $('#txtSalesQuotationProspectFilter').val(),
        "from_date"     : $('#txtFilterSalesQuotationFromDate').val(),
        "to_date"       : $('#txtFilterSalesQuotationToDate').val(),
        "filter_date"   : $('#cmbSalesQuotationFilterDate').val(),
        "status"        : $('#cmbSalesQuotationStatusFilter').val(),
    } ;
    var url  = "index.pzx?c=" + sales_quotation_url + "&t=" + C_SALES_QUOTATION_FILTER  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}
function populateContactDetail() {
    showProgress("Loading Contact Detail" ) ;
    
    var data = { "type": "_CONTACT_DETAIL", "cust_id": $('#cobSalesQuotationCustomerCode').val(), "contact_id": $('#cobSalesQuotationContact').val(), } ;
    var url  = "index.pzx?c=" + sales_quotation_url + "&t=" + "_CONTACT_DETAIL" + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}
function populateCustomerContact() {
    showProgress("Loading Contact" ) ;
    
    var data = { "type": "_CUSTOMER_CONTACT", "cust_id": $('#cobSalesQuotationCustomerCode').val(), } ;
    var url  = "index.pzx?c=" + sales_quotation_url + "&t=" + "_CUSTOMER_CONTACT" + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}
// function populateButtons(module) {
//     switch(module) {
//         case "ITEMS":
//             $('#btnSaveSalesQuotation').attr('onclick','addRecord("'+module+'")');
//             break;
//     }
// }
function addRecord() {
    saveRecord(C_SALES_QUOTATION_ADD);
}
function updateRecord() {
    saveRecord(C_SALES_QUOTATION_UPDATE);
}
function saveRecord(type) {
    showProgress("Save Details" ) ;
    
    if(validateRecord()) {
        var data = {
            "type"              : type,
            "id"                : $('#txtSalesQuotationID').val(), 
            "bu_id"             : $('#cobSalesQuotationBU').val(), 
            "type_id"           : $('#cobSalesQuotationType').val(), 
            "quot_number"       : $('#txtSalesQuotationNumber').val(),
            "cust_id"           : $('#cobSalesQuotationCustomerCode').val(),
            "contact_id"        : $('#cobSalesQuotationContact').val(),
            "contact_email"     : $('#txtSalesQuotationEmail').val(),
            "contact_mobile"    : $('#txtSalesQuotationMobile').val(),
            "contact_phone"     : $('#txtSalesQuotationTelephone').val(),
            "curr_id"           : $('#cobSalesQuotationCurrency').val(),
            "is_prospect"       : ($('#chkSwitch').is(":checked") == false ? 0:1),
            "prospect_name"     : $('#txtSalesQuotationProspectName').val(),
            "prospect_contact"  : $('#txtSalesQuotationProspectContact').val(),
            "title"             : $('#txtSalesQuotationTitle').val(),
            "add_contact"       : $('#txtSalesQuotationAddContact').val(),
            "preferred_inv_date"    : $('#txtSalesQuotationPreferredInvoiceDate').val(),
            "probability"       : $('#txtSalesQuotationProbability').val(),
            "exp_accept_date"   : $('#txtSalesQuotationExpectedAcceptDate').val(),
            "exp_pay_date"      : $('#txtSalesQuotationExpectedPayDate').val(),
            "percentage_payment"    : $('#txtSalesQuotationPercentagePayment').val(),
            "user_defined_1"    : typeof $('#txtSalesQuotationUserDefined1').val() === undefined ? "" : $('#txtSalesQuotationUserDefined1').val() ,
            "user_defined_2"    : typeof $('#txtSalesQuotationUserDefined2').val() === undefined ? "" : $('#txtSalesQuotationUserDefined2').val() ,
            "user_defined_3"    : typeof $('#txtSalesQuotationUserDefined3').val() === undefined ? "" : $('#txtSalesQuotationUserDefined3').val() ,
            "user_defined_4"    : typeof $('#txtSalesQuotationUserDefined4').val() === undefined ? "" : $('#txtSalesQuotationUserDefined4').val() ,

            //issue to solve
            "issue"             : $('#txtSalesIssue').val(),

            //item
            "items"             : getItems(), 
            "items_id"          : $('#txtSalesQuotationItemsId').val(),
            "sub_total"         : $('#txtsalesitemsubtotal').val(),
            "disc_type"         : $('#cobsalesitemdisctype').val(),
            "disc_percentage"   : $('#txtsalesitemdiscpercentage').val(),
            "disc_total"        : $('#txtsalesitemdisctotal').val(),
            "gst_percentage"    : $('#txtsalesitemgstpercentage').val(),
            "gst_total"         : $('#txtsalesitemgsttotal').val(),
            "grand_total"       : $('#txtsalesitemgrandtotal').val(),
            "qty_total"         : $('#txtsalesitemqtytotal').val(),            

            
            //maintenance & support
            "maintenance"                   : getMaintenance(),
            "maintenance_id"                : $('#txtSalesMaintenanceId').val(),
            "maintenance_currency"          : $('#lblSalesMaintenanceCurr').text(),
            "subtotal_maintenance"          : $('#txtSalesMaintenanceSubtotal').val(),
            "disc_type_maintenance"         : $('#cobSalesMaintenanceDiscType').val(),
            "disc_percentage_maintenance"   : $('#txtSalesMaintenanceDiscPercentage').val(),
            "disc_total_maintenance"        : $('#txtSalesMaintenanceDiscTotal').val(),
            "gst_percentage_maintenance"    : $('#txtSalesMaintenanceGstPercentage').val(),
            "gst_total_maintenance"         : $('#txtSalesMaintenanceGstTotal').val(),
            "grand_total_maintenance"       : $('#txtSalesMaintenanceGrandTotal').val(),

            //project plan
            "project_plan"          : getProjectPlan(),
            "project_plan_id"       : $('#txtSalesProjectPlanId').val(),
            "project_plan_amount"   : $('#txtSalesProjectPlanTotalAmount').val(),
            "project_plan_currency" : $('#lblSalesProjectPlanCurr').text(),

            //appendix
            "appendix"          : getAppendix(),

            //cover
            "cover"             : getSalesQuotationCover(),

            //footer
            "footer"            : $('#txtSalesQuotationFooter').val(),

            //print preview selection and sequence no
            "issue_print"               : ($('#chkSelectIssue').is(":checked") == false ? 0:1),
            "issue_print_page"          : $('#txtPageIssue').val(),
            "items_print"               : ($('#chkSelectItems').is(":checked") == false ? 0:1),
            "items_print_page"          : $('#txtPageItems').val(),
            "maintenance_print"         : ($('#chkSelectMS').is(":checked") == false ? 0:1),
            "maintenance_print_page"     : $('#txtPageMS').val(),
            "project_print"             : ($('#chkSelectProject').is(":checked") == false ? 0:1),
            "project_print_page"        : $('#txtPageProject').val(),
            "cover_print"               : ($('#chkSelectCover').is(":checked") == false ? 0:1),
            "cover_print_page"          : $('#txtPageCover').val(),
            "footer_print"              : ($('#chkSelectFooter').is(":checked") == false ? 0:1),
            "footer_print_page"         : $('#txtPageFooter').val(),
            "appendix_print"            : ($('#chkSelectAppendix').is(":checked") == false ? 0:1),
            "appendix_print_page"       : $('#txtPageAppendix').val(),
            "add_appendix"              : $('#txtAdditionalAppendix').val(),
        };
        // console.log(data);
        var url  = "index.pzx?c=" + sales_quotation_url + "&t=" + type + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onSalesQuotationResponse,null) ;
    }
}
function copySalesQuotation() {
    showProgress("Copy Sales Quotation Details" ) ;
    var quot = $('#cmbReviseListSalesQuotation').val().split('|');
    var data = {
        "type"              : C_SALES_QUOTATION_COPY,
        "id"                : quot[0],
    }
    var url  = "index.pzx?c=" + sales_quotation_url + "&t=" + C_SALES_QUOTATION_COPY + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}
//new revision
function updateRevise(revise_type) {
    showProgress("Save Details" ) ;
    
    // var t = document.getElementById("cmbReviseListSalesQuotation");
    // var selectedText = t.options[t.selectedIndex].text;

    var quot = $('#cmbReviseListSalesQuotation').val().split('|');
    var data = {
        "type"              : C_SALES_QUOTATION_REVISE_UPDATE,
        "id"                : quot[0],
        "quot_number"       : $('#cmbReviseListSalesQuotation option:selected').text(),
        "revise_type"       : revise_type, //0 - internal, 1 - customer
    }
    var url  = "index.pzx?c=" + sales_quotation_url + "&t=" + C_SALES_QUOTATION_REVISE_UPDATE + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}
function validateRecord() {
    if ($('#cobSalesQuotationBU').val()=="") {        
        Swal.fire({
            title:"Warning",
            text: "Please select Business Unit.",
            type: "warning"
        });
        return false;
    }

    if ($('#cobSalesQuotationType').val()=="") {
        Swal.fire({
            title:"Warning",
            text: "Please select Type.",
            type: "warning"
        });
       
        return false;
    }

    if($('#chkSwitch').is(":checked")) {
        if ($('#txtSalesQuotationProspectName').blank()) {
            Swal.fire({
                title:"Warning",
                text: "Prospect Name cannot be blank",
                type: "warning"
            });
           
            return false;
        }
        if ($('#txtSalesQuotationProspectContact').blank()) {
            Swal.fire({
                title:"Warning",
                text: "Prospect Contact cannot be blank",
                type: "warning"
            });
           
            return false;
        }
    } else {        
        if ($('#cobSalesQuotationCustomerCode').val()=="") {
            Swal.fire({
                title:"Warning",
                text: "Please select Company Name.",
                type: "warning"
            });
        
            return false;
        }
    }

    if ($('#cobSalesQuotationCurrency').val()=="") {
        Swal.fire({
            title:"Warning",
            text: "Please select Currency.",
            type: "warning"
        });
       
        return false;
    }

    return true;
}
function onSalesQuotationResponse(obj,resp){
    if (resp.status != C_OK ) {
        Swal.fire('Error', resp.mesg, "error");
        return false;
    }
    // console.log(resp.data.headerData);
    if (resp.type == C_SALES_QUOTATION_ADD_VIEW || resp.type == C_SALES_QUOTATION_UPDATE_VIEW || resp.type == C_SALES_QUOTATION_APPROVAL_VIEW) {
        $('#reviseListSalesQuotationModal').modal('hide');
        $('#showSalesQuotationView').modal('hide');
        
        if($('div').hasClass('modal-backdrop')) {
            $('div').removeClass('modal-backdrop');
        }
        showScreen(resp);

        $("#subheader_title").html(resp.data.headTitle);
        if(resp.type == C_SALES_QUOTATION_ADD_VIEW) {
            clearSalesQuotation();
            $('#general :input').attr("disabled", true);
            $('#items :input').attr("disabled", true);
            $('#mands :input').attr("disabled", true);
            $('#mands :input').attr("disabled", true);
            $('#projectplan :input').attr("disabled", true);
            $('#cover :input').attr("disabled", true);
            $('#footer :input').attr("disabled", true);
            $('#appendix :input').attr("disabled", true);
            $('#attachment :input').attr("disabled", true);
            $('#cobSalesQuotationCurrency').val(resp.data.baseCurrency);
            $('#btnClearSalesQuotation').prop('disabled',false);
            $('#btnPreviewSalesQuotation').prop("disabled", true);
            $('#btnSaveSalesQuotation').prop('disabled',false);
            $('#btnSaveSalesQuotation').attr('onclick','javascript:addRecord()');
        } else if(resp.type == C_SALES_QUOTATION_UPDATE_VIEW) {
            clearSalesQuotation();
            $('#txtSalesQuotationID').val(resp.data.headerData.id);
            $('#txtSalesQuotationType').val(resp.data.headerData.revise_type);
            $('#cobSalesQuotationBU').val(resp.data.headerData.bu_id);
            $('#cobSalesQuotationType').val(resp.data.headerData.type_id);
            // if(resp.data.headerData.revise_type == 1) {
            //     $('#txtSalesQuotationNumber').val(resp.data.headerData.customer_quot_number);
            // } else {
            //     $('#txtSalesQuotationNumber').val(resp.data.headerData.quot_number);
            // }
            $('#txtSalesQuotationNumberInternal').val(resp.data.headerData.quot_number);
            $('#txtSalesQuotationNumber').val(resp.data.headerData.customer_quot_number);
            $('#txtSalesQuotationNumber').attr("readonly", false);
            $('#cobSalesQuotationCustomerCode').val(resp.data.headerData.cust_id);
            $('#cobSalesQuotationContact').html('');
            $('#cobSalesQuotationContact').append(resp.data.headerData.contact_opt);
            $('#cobSalesQuotationContact').val(resp.data.headerData.contact_id);
            $('#txtSalesQuotationEmail').val(resp.data.headerData.contact_email);
            $('#txtSalesQuotationMobile').val(resp.data.headerData.contact_mobile);
            $('#txtSalesQuotationTelephone').val(resp.data.headerData.contact_telephone);
            $('#cobSalesQuotationCurrency').val(resp.data.headerData.currency);
            $('#txtSalesQuotationTitle').val(resp.data.headerData.title);
            $('#txtSalesQuotationAddContact').val(resp.data.headerData.add_contact);
            $('#txtSalesQuotationPreferredInvoiceDate').val(resp.data.headerData.preferred_inv_date);
            $('#txtSalesQuotationProbability').val(resp.data.headerData.probability);
            $('#txtSalesQuotationExpectedAcceptDate').val(resp.data.headerData.exp_accept_date);
            $('#txtSalesQuotationExpectedPayDate').val(resp.data.headerData.exp_pay_date);
            $('#txtSalesQuotationPercentagePayment').val(resp.data.headerData.percentage_payment);

            if(typeof $('#txtSalesQuotationUserDefined1').val() !== undefined) {
                $('#txtSalesQuotationUserDefined1').val(resp.data.headerData.user_defined_1);
            }
            if(typeof $('#txtSalesQuotationUserDefined2').val() !== undefined) {
                $('#txtSalesQuotationUserDefined2').val(resp.data.headerData.user_defined_2);
            }
            if(typeof $('#txtSalesQuotationUserDefined3').val() !== undefined) {
                $('#txtSalesQuotationUserDefined3').val(resp.data.headerData.user_defined_3);
            }
            if(typeof $('#txtSalesQuotationUserDefined4').val() !== undefined) {
                $('#txtSalesQuotationUserDefined4').val(resp.data.headerData.user_defined_4);
            }

            var prospect = resp.data.headerData.is_prospect == 1 ? true:false;
            if(prospect) {
                $('#chkSwitch').prop("checked",true);
                $('#txtSalesQuotationProspectName').val(resp.data.headerData.prospect_name);
                $('#txtSalesQuotationProspectContact').val(resp.data.headerData.prospect_contact);
                
                $('#col_div').hide();
                $('#col_label').hide();
                $('#col_contact_div').hide();
                $('#col_contact_label').hide();

                $('#pro_div').show();
                $('#pro_label').show();
                $('#pro_contact_div').show();
                $('#pro_contact_label').show();
            } else {
                $('#chkSwitch').prop("checked",false);
                
                $('#col_div').show();
                $('#col_label').show();
                $('#col_contact_div').show();
                $('#col_contact_label').show();
            
                $('#pro_div').hide();
                $('#pro_label').hide();
                $('#pro_contact_div').hide();
                $('#pro_contact_label').hide();
            }
            
            //issue
            $('#txtSalesIssue').val(resp.data.headerData.issue);

            //items
            var items = JSON.parse(resp.data.headerData.items);
            if(items.length > 0) {
                showSalesQuotationItemData(items);
            }

            //appendix
            var appendix = JSON.parse(resp.data.headerData.appendix);
            if(appendix.length > 0) {
                showSalesQuotationAppendixData(appendix);
            }

            //project plan
            $('#lblSalesProjectPlanCurr').text(resp.data.headerData.project_plan_currency);
            $('#txtSalesProjectPlanTotalAmount').val(resp.data.headerData.project_plan_amount);
            $('#txtSalesProjectPlanId').val(resp.data.headerData.project_plan_id);

            var project_plan = JSON.parse(resp.data.headerData.project_plan);
            if(project_plan.length > 0) {
                showSalesQuotationProjectPlanData(project_plan);
            }

            //maintenance & support
            $('#lblSalesMaintenanceCurr').text(resp.data.headerData.maintenance_currency);
            $('#txtSalesMaintenanceId').val(resp.data.headerData.maintenance_id);
            $('#txtSalesMaintenanceSubtotal').val(resp.data.headerData.subtotal_maintenance);
            $('#cobSalesMaintenanceDiscType').val(resp.data.headerData.disc_type_maintenance);
            $('#txtSalesMaintenanceDiscPercentage').val(resp.data.headerData.disc_percentage_maintenance);
            $('#txtSalesMaintenanceDiscTotal').val(resp.data.headerData.disc_total_maintenance);
            $('#txtSalesMaintenanceGstPercentage').val(resp.data.headerData.gst_percentage_maintenance);
            $('#txtSalesMaintenanceGstTotal').val(resp.data.headerData.gst_total_maintenance);
            $('#txtSalesMaintenanceGrandTotal').val(resp.data.headerData.grand_total_maintenance);

            var maintenance = JSON.parse(resp.data.headerData.maintenance);
            if(maintenance.length > 0) {
                showSalesQuotationMaintenanceData(maintenance);
            }
            
            //cover
            var cover = JSON.parse(resp.data.headerData.cover);
            if(cover.length > 0) {
                showSalesQuotationCoverData(cover);
            }

            //footer
            $('#txtSalesQuotationFooter').val(resp.data.headerData.footer);

            //print preview selection and sequence no
            $('#chkSelectIssue').prop("checked", resp.data.headerData.issue_print);
            $('#txtPageIssue').val(resp.data.headerData.issue_print_page);
            $('#txtPageIssue').prop('disabled',!resp.data.headerData.issue_print);

            $('#chkSelectItems').prop("checked", resp.data.headerData.items_print);
            $('#txtPageItems').val(resp.data.headerData.items_print_page);
            $('#txtPageItems').prop('disabled',!resp.data.headerData.items_print);

            $('#chkSelectMS').prop("checked", resp.data.headerData.maintenance_print);
            $('#txtPageMS').val(resp.data.headerData.maintenance_print_page);
            $('#txtPageMS').prop('disabled',!resp.data.headerData.maintenance_print);

            $('#chkSelectProject').prop("checked", resp.data.headerData.project_print);
            $('#txtPageProject').val(resp.data.headerData.project_print_page);
            $('#txtPageProject').prop('disabled',!resp.data.headerData.project_print);

            $('#chkSelectCover').prop("checked", resp.data.headerData.cover_print);
            $('#txtPageCover').val(resp.data.headerData.cover_print_page);
            $('#txtPageCover').prop('disabled',!resp.data.headerData.cover_print);

            $('#chkSelectFooter').prop("checked", resp.data.headerData.footer_print);
            $('#txtPageFooter').val(resp.data.headerData.footer_print_page);
            $('#txtPageFooter').prop('disabled',!resp.data.headerData.footer_print);

            $('#chkSelectAppendix').prop("checked", resp.data.headerData.appendix_print);
            $('#txtPageAppendix').val(resp.data.headerData.appendix_print_page);
            $('#txtPageAppendix').prop('disabled',!resp.data.headerData.appendix_print);
            $('#txtAdditionalAppendix').val(resp.data.headerData.add_appendix);

            //button
            var status = resp.data.headerData.status;
            var revise_type = resp.data.headerData.revise_type;
            var revise_ver = resp.data.headerData.revise_ver;
            var customer_ver = resp.data.headerData.customer_ver;
            var printed = resp.data.headerData.printed;
            var active = resp.data.headerData.active;

            if(status==0) {
                //open
                $('#btnAcceptSalesQuotation').prop('disabled',true);
                $('#btnSaveSalesQuotation').prop('disabled',false);
                $('#btnSubmitSalesQuotation').prop('disabled',false);
                $('#btnIssueSalesQuotation').prop('disabled',true);
                $('#btnReviseSalesQuotation').prop('disabled',true);
                $('#btnSaveSalesQuotation').attr('onclick','javascript:updateRecord()');
                
                if(resp.data.headerData.revise_type == 1) {
                    if(resp.data.headerData.customer_ver != "0" && resp.data.headerData.customer_ver != "") {
                        disableInput(true);
                        
                        $('#btnSaveSalesQuotation').prop('disabled',false);
                        $('#btnReviseSalesQuotation').prop('disabled',false);
                        $('#btnReviseSalesQuotation').attr('onclick','javascript:openReviseModal()');

                        $('#items :input').attr("disabled", false);
                        $('#mands :input').attr("disabled", false);
                        $('#btnNewItem').prop("disabled", false);

                        $('#txtsalesitemsubtotal').prop("disabled", true);
                        $('#txtsalesitemgsttotal').prop("disabled", true);
                        $('#txtsalesitemgrandtotal').prop("disabled", true);
                        
                        $('#sales-quotation-item-list tr').each(function() {
                            if($(this).find("select").length > 0) {
                                $(this).find("input,button,textarea,select").prop("disabled", false);
                            } else {
                                $(this).find("input,button,textarea").prop("disabled", true);
                            }
                        });

                        $('#txtSalesMaintenanceSubtotal').prop("disabled", true);
                        $('#txtSalesMaintenanceGstTotal').prop("disabled", true);
                        $('#txtSalesMaintenanceGrandTotal').prop("disabled", true);

                        $('#sales-quotation-maintenance-list tr').each(function() {
                            $(this).find("input,button,textarea").prop("disabled", true);
                        });

                        $('#sales-quotation-projectplan-list tr').each(function() {
                            $(this).find("input,button,textarea").prop("disabled", true);
                        });
                    }
                } else {
                    if(resp.data.headerData.revise_ver != "0" && resp.data.headerData.revise_ver != "") {
                        disableInput(false);
                        $('#btnSaveSalesQuotation').prop('disabled',false);
                        $('#btnSubmitSalesQuotation').prop('disabled',false);
                        $('#btnIssueSalesQuotation').prop('disabled',true);
                        $('#btnReviseSalesQuotation').prop('disabled',true);
                        $('#btnAcceptSalesQuotation').prop('disabled',true);
                        $('#btnProformaInvoiceSalesQuotation').prop('disabled',true);
                    }
                }
                $('#btnCustomerReviseSalesQuotation').prop('disabled',true);
                $('#txtSalesQuotationExpectedAcceptDate').attr("disabled", true);
                $('#txtSalesQuotationExpectedPayDate').attr("disabled", true);
                $('#txtSalesQuotationPercentagePayment').attr("disabled", true);
            } else if(status==1) {
                //issued
                disableInput(true);
                $('#btnSubmitSalesQuotation').prop('disabled',true);
                $('#btnAcceptSalesQuotation').attr('disabled',false);
                $('#btnNewReviseSalesQuotation').prop('disabled',false);
                $('#btnCustomerReviseSalesQuotation').prop('disabled',false);
                $('#txtSalesQuotationExpectedAcceptDate').attr("disabled", false);
                if(resp.data.headerData.exp_accept_date == ""){
                    $('#txtSalesQuotationExpectedAcceptDate').attr("disabled", false);
                    $('#btnSaveSalesQuotation').prop('disabled',false);
                    $('#btnSaveSalesQuotation').attr('onclick','javascript:updateExpected()');
                }
            } if(status==2) {
                //revised
                if(resp.data.headerData.active == 1)
                    $('#btnSaveSalesQuotation').attr('onclick','javascript:updateRecord()');
                else {
                    disableInput(true);
                    $('#btnSubmitSalesQuotation').prop('disabled',true);
                    $('#btnAcceptSalesQuotation').attr('disabled',false);
                }
                $('#btnNewReviseSalesQuotation').prop('disabled',false);
                $('#btnCustomerReviseSalesQuotation').prop('disabled',false);
                if(resp.data.headerData.exp_accept_date == ""){
                    $('#txtSalesQuotationExpectedAcceptDate').attr("disabled", false);
                    $('#btnSaveSalesQuotation').prop('disabled',false);
                    $('#btnSaveSalesQuotation').attr('onclick','javascript:updateExpected()');
                }
            } if(status==3) {
                //accepted
                disableInput(true);
                $('#btnReviseSalesQuotation').prop('disabled',true);
                $('#btnAcceptSalesQuotation').prop('disabled',true);
                $('#btnSaveSalesQuotation').prop('disabled',true);
                $('#btnIssueSalesQuotation').prop('disabled',true);
                $('#btnSubmitSalesQuotation').prop('disabled',true);

                $('#btnProformaInvoiceSalesQuotation').prop('disabled',false);
                $('#btnProformaInvoiceSalesQuotation').attr('onclick',"openModalInvoice("+resp.data.headerData.printed+")");
                if(resp.data.headerData.exp_pay_date == ""){
                    $('#txtSalesQuotationExpectedPayDate').attr("disabled", false);
                    $('#txtSalesQuotationPercentagePayment').attr("disabled", false);
                    $('#btnSaveSalesQuotation').prop('disabled',false);
                    $('#btnSaveSalesQuotation').attr('onclick','javascript:updateExpected()');
                }
            } if(status==5) {
                //submitted
                disableInput(true);
                $('#btnSaveSalesQuotation').prop('disabled',true);
                $('#btnSubmitSalesQuotation').prop('disabled',true);
                $('#btnIssueSalesQuotation').prop('disabled',true);
                $('#btnReviseSalesQuotation').prop('disabled',true);
                $('#btnAcceptSalesQuotation').prop('disabled',true);
                $('#btnClosedSalesQuotation').prop('disabled',true);
                $('#btnNewReviseSalesQuotation').prop('disabled',true);
                $('#btnCustomerReviseSalesQuotation').prop('disabled',true);
            } if(status==6) {
                //approved
                disableInput(true);
                $('#btnSaveSalesQuotation').prop('disabled',true);
                $('#btnIssueSalesQuotation').prop('disabled',false);
                $('#btnSubmitSalesQuotation').prop('disabled',true);
                $('#btnReviseSalesQuotation').prop('disabled',true);
                $('#btnAcceptSalesQuotation').prop('disabled',true);

                //for revise
                if(resp.data.headerData.customer_ver == "0" || resp.data.headerData.customer_ver == "") {
                    $('#btnIssueSalesQuotation').attr('onclick','javascript:openIssueModal()');
                    $('#btnReviseSalesQuotation').prop('disabled',true);
                } else {
                    // if((resp.data.headerData.revise_ver != "0" && resp.data.headerData.revise_ver != "")) {
                        $('#btnIssueSalesQuotation').prop('disabled',true);
                        $('#btnReviseSalesQuotation').prop('disabled',false);
                        $('#btnReviseSalesQuotation').attr('onclick','javascript:openReviseModal()');
                    // }
                }
            } if(status==7) {
                //rejected
                $('#btnReviseSalesQuotation').prop('disabled',true);
                $('#btnAcceptSalesQuotation').prop('disabled',true);
                $('#btnSaveSalesQuotation').prop('disabled',true);
                $('#btnIssueSalesQuotation').prop('disabled',true);
                $('#btnSubmitSalesQuotation').prop('disabled',true);

                disableInput(true);
            }

            $('#btnPreviewSalesQuotation').attr('onclick','javascript:previewSalesQuotationPDF('+resp.data.headerData.id+')');
            $('#btnIssueSalesQuotation').attr('onclick','javascript:openIssueModal()');
            $('#btnReviseSalesQuotation').attr('onclick','javascript:openReviseModal()');
            $('#btnAcceptSalesQuotation').attr('onclick','javascript:acceptSalesQuotation()');

            if(resp.data.headerData.closed == 1) {
                $('#btnClosedSalesQuotation').prop('disabled',true);
                $('#txtSalesQuotationExpectedAcceptDate').attr("disabled", true);
                $('#txtSalesQuotationExpectedPayDate').attr("disabled", true);
                $('#txtSalesQuotationPercentagePayment').attr("disabled", true);
            } else {
                $('#btnClosedSalesQuotation').prop('disabled',false);
            }
            
            $('#txtSalesQuotationGrandTotal').val(resp.data.headerData.grand_total);
        } else if(resp.type == C_SALES_QUOTATION_APPROVAL_VIEW) {
            if($('div').hasClass('modal-backdrop')) {
                $('div').removeClass('modal-backdrop')
            }
            clearSalesQuotation();
            $('#txtSalesQuotationID').val(resp.data.headerData.id);
            $('#cobSalesQuotationBU').val(resp.data.headerData.bu_id);
            $('#cobSalesQuotationType').val(resp.data.headerData.type_id);
            $('#txtSalesQuotationNumberInternal').val(resp.data.headerData.quot_number);
            $('#txtSalesQuotationNumber').val(resp.data.headerData.customer_quot_number);
            $('#txtSalesQuotationNumber').attr("readonly", false);
            $('#cobSalesQuotationCustomerCode').val(resp.data.headerData.cust_id);
            $('#cobSalesQuotationContact').html('');
            $('#cobSalesQuotationContact').append(resp.data.headerData.contact_opt);
            $('#cobSalesQuotationContact').val(resp.data.headerData.contact_id);
            $('#txtSalesQuotationEmail').val(resp.data.headerData.contact_email);
            $('#txtSalesQuotationMobile').val(resp.data.headerData.contact_mobile);
            $('#txtSalesQuotationTelephone').val(resp.data.headerData.contact_telephone);
            $('#cobSalesQuotationCurrency').val(resp.data.headerData.currency);
            $('#txtSalesQuotationTitle').val(resp.data.headerData.title);
            $('#txtSalesQuotationAddContact').val(resp.data.headerData.add_contact);
            $('#txtSalesQuotationPreferredInvoiceDate').val(resp.data.headerData.preferred_inv_date);
            $('#txtSalesQuotationProbability').val(resp.data.headerData.probability);
            $('#txtSalesQuotationExpectedAcceptDate').val(resp.data.headerData.exp_accept_date);
            $('#txtSalesQuotationExpectedPayDate').val(resp.data.headerData.exp_pay_date);
            $('#txtSalesQuotationPercentagePayment').val(resp.data.headerData.percentage_payment);
            
            if(typeof $('#txtSalesQuotationUserDefined1').val() !== undefined) {
                $('#txtSalesQuotationUserDefined1').val(resp.data.headerData.user_defined_1);
            }
            if(typeof $('#txtSalesQuotationUserDefined2').val() !== undefined) {
                $('#txtSalesQuotationUserDefined2').val(resp.data.headerData.user_defined_2);
            }
            if(typeof $('#txtSalesQuotationUserDefined3').val() !== undefined) {
                $('#txtSalesQuotationUserDefined3').val(resp.data.headerData.user_defined_3);
            }
            if(typeof $('#txtSalesQuotationUserDefined4').val() !== undefined) {
                $('#txtSalesQuotationUserDefined4').val(resp.data.headerData.user_defined_4);
            }
            var prospect = resp.data.headerData.is_prospect == 1 ? true:false;
            if(prospect) {
                $('#chkSwitch').prop("checked",true);
                $('#txtSalesQuotationProspectName').val(resp.data.headerData.prospect_name);
                $('#txtSalesQuotationProspectContact').val(resp.data.headerData.prospect_contact);
                
                $('#col_div').hide();
                $('#col_label').hide();
                $('#col_contact_div').hide();
                $('#col_contact_label').hide();

                $('#pro_div').show();
                $('#pro_label').show();
                $('#pro_contact_div').show();
                $('#pro_contact_label').show();
            } else {
                $('#chkSwitch').prop("checked",false);
                
                $('#col_div').show();
                $('#col_label').show();
                $('#col_contact_div').show();
                $('#col_contact_label').show();
            
                $('#pro_div').hide();
                $('#pro_label').hide();
                $('#pro_contact_div').hide();
                $('#pro_contact_label').hide();
            }
            
            //issue
            $('#txtSalesIssue').val(resp.data.headerData.issue);

            //items
            var items = JSON.parse(resp.data.headerData.items);
            if(items.length > 0) {
                showSalesQuotationItemData(items);
            }

            //appendix
            var appendix = JSON.parse(resp.data.headerData.appendix);
            if(appendix.length > 0) {
                showSalesQuotationAppendixData(appendix);
            }

            //project plan
            $('#lblSalesProjectPlanCurr').text(resp.data.headerData.project_plan_currency);
            $('#txtSalesProjectPlanTotalAmount').val(resp.data.headerData.project_plan_amount);
            $('#txtSalesProjectPlanId').val(resp.data.headerData.project_plan_id);

            var project_plan = JSON.parse(resp.data.headerData.project_plan);
            if(project_plan.length > 0) {
                showSalesQuotationProjectPlanData(project_plan);
            }

            //maintenance & support
            $('#lblSalesMaintenanceCurr').text(resp.data.headerData.maintenance_currency);
            $('#txtSalesMaintenanceId').val(resp.data.headerData.maintenance_id);
            $('#txtSalesMaintenanceSubtotal').val(resp.data.headerData.subtotal_maintenance);
            $('#cobSalesMaintenanceDiscType').val(resp.data.headerData.disc_type_maintenance);
            $('#txtSalesMaintenanceDiscPercentage').val(resp.data.headerData.disc_percentage_maintenance);
            $('#txtSalesMaintenanceDiscTotal').val(resp.data.headerData.disc_total_maintenance);
            $('#txtSalesMaintenanceGstPercentage').val(resp.data.headerData.gst_percentage_maintenance);
            $('#txtSalesMaintenanceGstTotal').val(resp.data.headerData.gst_total_maintenance);
            $('#txtSalesMaintenanceGrandTotal').val(resp.data.headerData.grand_total_maintenance);
           
            var maintenance = JSON.parse(resp.data.headerData.maintenance);
            if(maintenance.length > 0) {
                showSalesQuotationMaintenanceData(maintenance);
            }
            
            //cover
            var cover = JSON.parse(resp.data.headerData.cover);
            if(cover.length > 0) {
                showSalesQuotationCoverData(cover);
            }

            //footer
            $('#txtSalesQuotationFooter').val(resp.data.headerData.footer);

            //print preview selection and sequence no
            $('#chkSelectIssue').prop("checked", resp.data.headerData.issue_print);
            $('#txtPageIssue').val(resp.data.headerData.issue_print_page);
            $('#txtPageIssue').prop('disabled',!resp.data.headerData.issue_print);

            $('#chkSelectItems').prop("checked", resp.data.headerData.items_print);
            $('#txtPageItems').val(resp.data.headerData.items_print_page);
            $('#txtPageItems').prop('disabled',!resp.data.headerData.items_print);

            $('#chkSelectMS').prop("checked", resp.data.headerData.maintenance_print);
            $('#txtPageMS').val(resp.data.headerData.maintenance_print_page);
            $('#txtPageMS').prop('disabled',!resp.data.headerData.maintenance_print);

            $('#chkSelectProject').prop("checked", resp.data.headerData.project_print);
            $('#txtPageProject').val(resp.data.headerData.project_print_page);
            $('#txtPageProject').prop('disabled',!resp.data.headerData.project_print);

            $('#chkSelectCover').prop("checked", resp.data.headerData.cover_print);
            $('#txtPageCover').val(resp.data.headerData.cover_print_page);
            $('#txtPageCover').prop('disabled',!resp.data.headerData.cover_print);

            $('#chkSelectFooter').prop("checked", resp.data.headerData.footer_print);
            $('#txtPageFooter').val(resp.data.headerData.footer_print_page);
            $('#txtPageFooter').prop('disabled',!resp.data.headerData.footer_print);

            $('#chkSelectAppendix').prop("checked", resp.data.headerData.appendix_print);
            $('#txtPageAppendix').val(resp.data.headerData.appendix_print_page);
            $('#txtPageAppendix').prop('disabled',!resp.data.headerData.appendix_print);
            $('#txtAdditionalAppendix').val(resp.data.headerData.add_appendix);

            disableInput(true);
            // $('#btnClearSalesQuotation').prop('disabled',true);
            $('#btnSaveSalesQuotation').prop('disabled',true);
            $('#btnPreviewSalesQuotation').attr('onclick','javascript:previewSalesQuotationPDF('+resp.data.headerData.id+');');
            $('#btnSubmitSalesQuotation').prop('disabled',true);
            $('#btnIssueSalesQuotation').prop('disabled',true);
            $('#btnReviseSalesQuotation').prop('disabled',true);
            $('#btnAcceptSalesQuotation').prop('disabled',true);
            $('#btnClosedSalesQuotation').prop('disabled',true);
            // $('#btnRetrieveSalesQuotation').prop('disabled',true);

            if(resp.data.headerData.status == 5) { //submitted
                $('#btnApprovalSalesQuotation').show();
                $('#btnApprovalSalesQuotation').prop('disabled',false);
                $('#btnApprovalSalesQuotation').attr('onclick','javascript:openApprovalModal('+resp.data.headerData.id+',"'+resp.data.headerData.customer_quot_number+'");');
            } else if(resp.data.headerData.status == 6) { //approved
                console.log(resp.data.headerData);
                if(resp.data.headerData.customer_ver == "0" || resp.data.headerData.customer_ver == "") {
                    $('#btnIssueSalesQuotation').prop('disabled',false);
                    $('#btnIssueSalesQuotation').attr('onclick','javascript:openIssueModal()');
                    $('#btnReviseSalesQuotation').prop('disabled',true);
                } else {
                    // if((resp.data.headerData.revise_ver != "0" && resp.data.headerData.revise_ver != "")) {
                        $('#btnIssueSalesQuotation').prop('disabled',true);
                        $('#btnReviseSalesQuotation').prop('disabled',false);
                        $('#btnReviseSalesQuotation').attr('onclick','javascript:openReviseModal()');
                    // }
                }
                updateViewDetail(resp.data.headerData.id);
            } else if(resp.data.headerData.status == 7) { //rejected
                updateViewDetail(resp.data.headerData.id);
            }
        }
        
        $('#btnClearSalesQuotation').prop('disabled',false);
        $('#btnPreviewSalesQuotation').prop("disabled", false);
    } else if (resp.type == "_CUSTOMER_CONTACT") {
        $('#cobSalesQuotationContact').html('');
        $('#cobSalesQuotationContact').append(resp.data);
    } else if (resp.type == "_CONTACT_DETAIL") {
        $('#txtSalesQuotationEmail').val('');
        $('#txtSalesQuotationMobile').val('');
        $('#txtSalesQuotationTelephone').val('');
        $('#txtSalesQuotationEmail').val(resp.data.contact_email);
        $('#txtSalesQuotationMobile').val(resp.data.contact_mobile);
        $('#txtSalesQuotationTelephone').val(resp.data.contact_telephone);
    } else if (resp.type == C_SALES_QUOTATION_ADD) {
        Swal.fire("Success", resp.mesg, "success");
        $('#txtSalesQuotationID').val(resp.data.id);
        $('#txtSalesQuotationNumberInternal').val(resp.data.quot_number);
        $('#txtSalesQuotationNumber').val(resp.data.customer_quot_number);
        $('#txtSalesQuotationItemsId').val(resp.data.items_id == null ? -1:resp.data.items_id);

        disableInput(false);
        $('#btnSaveSalesQuotation').attr('onclick','javascript:updateRecord()');
        $('#btnPreviewSalesQuotation').prop("disabled", false);
        $('#btnPreviewSalesQuotation').attr('onclick','javascript:previewSalesQuotationPDF('+resp.data.id+')');
        // $('#btnIssueSalesQuotation').attr('onclick','javascript:openIssueModal()');
        // $('#btnReviseSalesQuotation').attr('onclick','javascript:openReviseModal()');
        // $('#btnAcceptSalesQuotation').attr('onclick','javascript:acceptSalesQuotation()');

        // $('#btnReviseSalesQuotation').prop('disabled',true);
        // $('#btnAcceptSalesQuotation').prop('disabled',true);
        // $('#btnSaveSalesQuotation').prop('disabled',false);
        // $('#btnIssueSalesQuotation').prop('disabled',false);

        $('#btnApprovalSalesQuotation').prop('disabled',true);
        $('#btnIssueSalesQuotation').prop('disabled',true);
        $('#btnReviseSalesQuotation').prop('disabled',true);
        $('#btnAcceptSalesQuotation').prop('disabled',true);
        $('#btnClosedSalesQuotation').prop('disabled',true);
    } else if (resp.type == C_SALES_QUOTATION_UPDATE) {
        Swal.fire("Success", resp.mesg, "success");
        $('#txtSalesQuotationID').val(resp.data.id);
        $('#txtSalesQuotationItemsId').val(resp.data.items_id);
    } else if(resp.type == C_SALES_QUOTATION_FILTER) {
        $('#showSalesQuotationView').modal('show');
        $('#sales-quotation-list-table').html('');
        $('#sales-quotation-list-table').append(resp.data.htmlStr);
    } else if (resp.type == C_SALES_QUOTATION_DELETE) {
        Swal.fire("Success", resp.mesg, "success");
        filterSalesQuotation();
        showAddSalesQuotation();
    } else if (resp.type == "SEND_SALES_QUOTATION_ISSUE"){
        Swal.fire("Success", resp.mesg, "success");
        $('#issueSalesQuotationModal').modal('hide');
        showAddSalesQuotation();
    } else if (resp.type == "SEND_SALES_QUOTATION_REVISE"){
        Swal.fire("Success", resp.mesg, "success");
        $('#reviseSalesQuotationModal').modal('hide');
        showAddSalesQuotation();
    } else if (resp.type == "SALES_QUOTATION_ACCEPT"){
        Swal.fire("Success", resp.mesg, "success");
        $('#btnReviseSalesQuotation').prop('disabled',true);
        $('#btnAcceptSalesQuotation').prop('disabled',true);
        $('#btnSaveSalesQuotation').prop('disabled',true);
        $('#btnIssueSalesQuotation').prop('disabled',true);
        $('#btnClosedSalesQuotation').prop('disabled',false);
        $('#btnProformaInvoiceSalesQuotation').prop('disabled',false);
    } else if (resp.type == C_ADD_UPLOAD_ATTACH_SALES_QUOT_VIEW ) {
        $('#modaluploadDocSalesQuotationContent').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 ++;
            }
            $("#salesquotation_docs_upload").html(strHtml);
        });
        
        // var strBtn = resp.data.button;
        // $('#modaluploadDocJobCentreButtonContent').html(strBtn);

    } else if (resp.type == C_ADD_UPLOAD_ATTACH_SALES_QUOT_REVISE_VIEW ) {
        $('#modaluploadDocReviseSalesQuotationContent').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 ++;
            }
            $("#salesquotation_docs_upload").html(strHtml);
        });
    } else if (resp.type == "C_SALES_QUOTATION_SUBMIT_ATTACH_VIEW" ) {
        $('#modaluploadDocSubmitSalesQuotationContent').html(resp.data.content);
    } else if(resp.type == C_SALES_QUOTATION_REVISE_LIST) {
        $('#cmbReviseListSalesQuotation').html('');
        $('#cmbReviseListSalesQuotation').append(resp.data.list);
        
        if(resp.data.status==3 || resp.data.status==4 || resp.data.status==5 || resp.data.status==6) {
            $('#btnNewReviseSalesQuotation').prop('disabled',true);
            $('#btnCustomerReviseSalesQuotation').prop('disabled',true);
        } else {            
            $('#btnNewReviseSalesQuotation').prop('disabled',false);
            if(resp.data.approver) {
                $('#btnCustomerReviseSalesQuotation').prop('disabled',false);
            } else {                
                $('#btnCustomerReviseSalesQuotation').prop('disabled',true);
            }
        }
    } else if(resp.type == C_SALES_QUOTATION_REVISE_UPDATE || resp.type == C_SALES_QUOTATION_COPY) {
        Swal.fire("Success", resp.mesg, "success");
        showEditSalesQuotation(resp.data.id, resp.data.revise_type, null);
    } else if (resp.type == "SEND_SALES_QUOTATION_SUBMIT"){
        Swal.fire("Success", resp.mesg, "success");
        $('#submitSalesQuotationModal').modal('hide');
        showAddSalesQuotation();
    } else if (resp.type == "RESET_QUOTATION_RN"){
        // console.log(resp.mesg);
    } else {
        Swal.fire("Success", resp.mesg, "success");
        console.log(resp.mesg);
    } 
}
function disableInput(lControl) { 
    // $('#div-bu :input').attr("disabled", lControl);
    $('#cobSalesQuotationBU').prop('disabled',true);
    $('#div-quot :input').attr("disabled", lControl);
    $('#div-detail :input').attr("disabled", lControl);
    $('#div-contact :input').attr("disabled", lControl);
    $('#div-expected :input').attr("disabled", lControl);
    $('#div-buttons :input').attr("disabled", lControl);
    $('#general :input').attr("disabled", lControl);
    $('#items :input').attr("disabled", lControl);
    $('#mands :input').attr("disabled", lControl);
    $('#projectplan :input').attr("disabled", lControl);
    $('#cover :input').attr("disabled", lControl);
    $('#footer :input').attr("disabled", lControl);
    $('#appendix :input').attr("disabled", lControl);
    $('#attachment :input').attr("disabled", lControl);

    $('#div-cover-print :input').attr("disabled", lControl);
    $('#btnSaveTempCover').attr("disabled", lControl);
    $('#btnLoadTempCover').attr("disabled", lControl);
    $('#txtCoverDesc1').attr("disabled", lControl);
    $('#txtCoverDesc2').attr("disabled", lControl);
    $('#txtCoverDesc3').attr("disabled", lControl);
    $('#txtCoverUpload1').attr("disabled", lControl);
    $('#txtCoverUpload2').attr("disabled", lControl);
    $('#txtCoverUpload3').attr("disabled", lControl);
    $('#txtCoverFilename1').attr("disabled", lControl);
    $('#txtCoverFilename2').attr("disabled", lControl);
    $('#txtCoverFilename3').attr("disabled", lControl);
    $('#btnCoverUpload1').attr("disabled", lControl);
    $('#btnCoverUpload2').attr("disabled", lControl);
    $('#btnCoverUpload3').attr("disabled", lControl);
    $('#btnRemoveCover1').attr("disabled", lControl);
    $('#btnRemoveCover2').attr("disabled", lControl);
    $('#btnRemoveCover3').attr("disabled", lControl);

    $('#txtSalesQuotationNumberInternal').prop("disabled", true);
    $('#txtSalesQuotationNumber').prop("disabled", true);
}
function clearSalesQuotation(control) {
    if(control) {
        sales_quotation_obj   = null;
        sales_quotation_idx   = 1;
        sales_item_idx = 1;
        sales_item_counter = 0;
        sales_item_section_idx = 0;
        sales_apdx_idx = 0;
        sales_projectplan_idx = 0;
        sales_ms_idx = 0;
        sales_cover_idx = 1;
    }

    disableInput(false);
    $('#txtSalesQuotationID').val('-1');
    $('#cobSalesQuotationBU').val('');
    $('#cobSalesQuotationBU').prop("disabled", false);
    $('#cobSalesQuotationType').val('');
    $('#txtSalesQuotationNumberInternal').val('AUTO');
    $('#txtSalesQuotationNumber').val('AUTO');
    $('#cobSalesQuotationCustomerCode').val('');
    $('#cobSalesQuotationContact').val('');
    $('#cobSalesQuotationContact').html('');
    var opt_contact = '<option value="0">-- Select --</option>';
    $('#cobSalesQuotationContact').append(opt_contact);
    $('#txtSalesQuotationEmail').val('');
    $('#txtSalesQuotationMobile').val('');
    $('#txtSalesQuotationTelephone').val('');
    $('#cobSalesQuotationCurrency').val('');
    $('#chkSwitch').prop("checked",false);
    $('#txtSalesQuotationProspectName').val('');
    $('#txtSalesQuotationProspectContact').val('');
    $('#txtSalesQuotationTitle').val('');
    $('#txtSalesQuotationAddContact').val('');
    // $('#txtSalesQuotationPreferredInvoiceDate').val('');    
    $('#txtSalesQuotationExpectedAcceptDate').val('');
    $('#txtSalesQuotationExpectedPayDate').val('');
    $('#txtSalesQuotationPercentagePayment').val('');
    $('#txtSalesQuotationProbability').val('');

    if(typeof $('#txtSalesQuotationUserDefined1').val() !== undefined) {
        $('#txtSalesQuotationUserDefined1').val('');
    }
    if(typeof $('#txtSalesQuotationUserDefined2').val() !== undefined) {
        $('#txtSalesQuotationUserDefined2').val('');
    }
    if(typeof $('#txtSalesQuotationUserDefined3').val() !== undefined) {
        $('#txtSalesQuotationUserDefined3').val('');
    }
    if(typeof $('#txtSalesQuotationUserDefined4').val() !== undefined) {
        $('#txtSalesQuotationUserDefined4').val('');
    }
    // $('#txtSalesQuotationGrandTotal').val('0');
    
    clearItems();
    clearAppendix();
    clearProjectPlan();
    clearMaintenance();
    clearCover();

    $('#txtSalesQuotationFooter').val('');
    $('#txtSalesIssue').val('');

    $('#chkSelectIssue').prop("checked",false);
    $('#txtPageIssue').val('');
    $('#txtPageIssue').prop('disabled','disabled');
    $('#chkSelectItems').prop("checked",false);
    $('#txtPageItems').val('');
    $('#txtPageItems').prop('disabled','disabled');
    $('#chkSelectMS').prop("checked",false);
    $('#txtPageMS').val('');
    $('#txtPageMS').prop('disabled','disabled');
    $('#chkSelectProject').prop("checked",false);
    $('#txtPageProject').val('');
    $('#txtPageProject').prop('disabled','disabled');
    $('#chkSelectCover').prop("checked",false);
    $('#txtPageCover').val('');
    $('#txtPageCover').prop('disabled','disabled');
    $('#chkSelectFooter').prop("checked",false);
    $('#txtPageFooter').val('');
    $('#txtPageFooter').prop('disabled','disabled');
    $('#chkSelectAppendix').prop("checked",false);
    $('#txtPageAppendix').val('');
    $('#txtPageAppendix').prop('disabled','disabled');
    
    $('#btnSaveSalesQuotation').attr('onclick','javascript:addRecord()');
    $('#btnPreviewSalesQuotation').attr('onclick','javascript:previewSalesQuotationPDF()');
    $('#btnIssueSalesQuotation').attr('onclick','javascript:openIssueModal()');
    $('#btnReviseSalesQuotation').attr('onclick','');
    $('#btnAcceptSalesQuotation').attr('onclick','');

    $('#btnClearSalesQuotation').prop('disabled',true);
    $('#btnPreviewSalesQuotation').prop("disabled", true);
    $('#btnSaveSalesQuotation').prop('disabled',true);
    $('#btnSubmitSalesQuotation').prop('disabled',true);
    $('#btnIssueSalesQuotation').prop('disabled',true);
    $('#btnReviseSalesQuotation').prop('disabled',true);
    $('#btnAcceptSalesQuotation').prop('disabled',true);
    $('#btnClosedSalesQuotation').prop('disabled',true);    
    // $('#btnRetrieveSalesQuotation').prop('disabled',true);
    $('#btnApprovalSalesQuotation').prop('disabled',true);
    $('#btnProformaInvoiceSalesQuotation').prop('disabled',true);
    $('#btnNewReviseSalesQuotation').prop('disabled',false);
    $('#btnCustomerReviseSalesQuotation').prop('disabled',false);

    $('#btnApprovalSalesQuotation').hide();
}

function openIssueModal() {
    Swal.fire({
        title: "Send Issue Confirmation",
        text: "If you change any data, make sure to save it first before continue it. Continue?'",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Continue",
        cancelButtonText: "Back",
        confirmButtonColor: '#2754e6',
    }).then(function(result) {
        if (result.value) {
            $('#issueSalesQuotationModal').modal('show');

            if($('#chkSwitch').is(":checked")) {
                $('#labelSalesQuotationContactName').text($('#txtSalesQuotationProspectContact').val());
            } else {
                var contact = $('#cobSalesQuotationContact :selected').text();
                $('#labelSalesQuotationContactName').text(contact);
            }

            var email = $('#txtSalesQuotationEmail').val();
            $('#salesQuotationIssueTo').val(email);

            var id = $('#txtSalesQuotationID').val();
            addSalesQuotationDocsView(id,this);
        }
    });
}

function sendIssueSalesQuotation() {
    var data = { 
        "id"            : $('#txtSalesQuotationID').val(),
        "to_email"      : $('#salesQuotationIssueTo').val(),
        "contact"       : $('#labelSalesQuotationContactName').text(),
        "cc_email"      : $('#salesQuotationIssueCC').val(),
        "remarks"       : $('#salesQuotationIssueRemarks').val(),
        "type"          : "SEND_SALES_QUOTATION_ISSUE"
        };
    var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,sales_quotation_obj) ;
}

function openReviseModal() {
    Swal.fire({
        title: "Send Revise Confirmation",
        text: "If you change any data, make sure to save it first before continue it. Continue?'",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Continue",
        cancelButtonText: "Back",
        confirmButtonColor: '#2754e6',
    }).then(function(result) {
        if (result.value) {
            $('#reviseSalesQuotationModal').modal('show');

            if($('#chkSwitch').is(":checked")) {
                $('#labelSalesQuotationName').text($('#txtSalesQuotationProspectContact').val());
            } else {
                var contact = $('#cobSalesQuotationContact :selected').text();
                $('#labelSalesQuotationName').text(contact);
            }
            
            var email = $('#txtSalesQuotationEmail').val();
            $('#salesQuotationReviseTo').val(email);

            var id = $('#txtSalesQuotationID').val();
            addSalesQuotationReviseDocsView(id,this);
        }
    });
}

function sendReviseSalesQuotation() {
    var data = { 
        "id"            : $('#txtSalesQuotationID').val(),
        "quot_number"   : $('#txtSalesQuotationNumber').val(),
        "to_email"      : $('#salesQuotationReviseTo').val(),
        "contact"       : $('#labelSalesQuotationName').text(),
        "cc_email"      : $('#salesQuotationReviseCC').val(),
        "remarks"       : $('#salesQuotationReviseRemarks').val(),
        "type"          : "SEND_SALES_QUOTATION_REVISE",
        };
    var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,sales_quotation_obj) ;
}

function acceptSalesQuotation() {
    var data = { 
        "id"            : $('#txtSalesQuotationID').val(),
        "type"          : "SALES_QUOTATION_ACCEPT"
        };
    var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,sales_quotation_obj) ;
}

function openModalRevisionSalesQuotation(ref_id, status, approver) {
    $('#reviseListSalesQuotationModal').modal('show');
    var data  = { "type": C_SALES_QUOTATION_REVISE_LIST, "id": ref_id, "status": status, "approver": approver } ;
    var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + C_SALES_QUOTATION_REVISE_LIST  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}

function editSalesQuotation(edit_type) {
    $('#reviseListSalesQuotationModal').modal('hide');
    // screen_index = 0;

    var quot = $('#cmbReviseListSalesQuotation').val().split('|');
    var data  = { "type": C_SALES_QUOTATION_UPDATE_VIEW, "id" : quot[0], "revise_type": quot[1], "index":screen_index } ;
    var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + C_SALES_QUOTATION_UPDATE_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}

//==================================================================================
//document
function addSalesQuotationDocsView(id, obj) {
    // console.log(id);
    var data  = { "type": C_ADD_UPLOAD_ATTACH_SALES_QUOT_VIEW, "id" : id } ;
    var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + C_ADD_UPLOAD_ATTACH_SALES_QUOT_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}

function addSalesQuotationReviseDocsView(id, obj) {
    var data  = { "type": C_ADD_UPLOAD_ATTACH_SALES_QUOT_REVISE_VIEW, "id" : id} ;
    var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + C_ADD_UPLOAD_ATTACH_SALES_QUOT_REVISE_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}

function addSalesQuotationDocs() {
    if($('#salesquotation_docs_upload').text().trim() != "") {
        $("#btnSalesQuotationCancelUpload").prop('disabled',true);
        var url  = "index.pzx?c=" + sales_quotation_url + "&t=" + C_ADD_UPLOAD_ATTACH_SALES_QUOT_DOC  + "&d=" + new Date().getTime() + "&salesquotation_id=" + $("#salesquotation_id").val() ;
        $('#salesquotation_docs_upload').show() ;
        ajaxUpload(upload_form,url,salesQuotationShowUploadEnd);

    }
    return false;
}

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

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

function saveSalesQuotationDoc() {
    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_SAVE_ATTACHMENT,
                 "salesQuotationId"  : $('#salesquotation_id').val(), 
                 "docIds"   : docIds, 
                 // "descList" : descList };
                };
    var url  = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationDocumentResponse,null) ;
}

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

function removeSalesQuotationFile(docId) {
    Swal.fire({
        title: "Delete Attachment",
        text: "Are you sure you want to delete the attachment?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        confirmButtonColor: '#2754e6',
    }).then(function(result) {
        if (result.value) {
            var data  = { "type"    : C_DELETE_ATTACHMENT,
                 "salesquotation_id" : $('#salesquotation_id').val(), 
                 "doc_id"   : docId};

            var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + C_DELETE_ATTACHMENT  + "&d=" + new Date().getTime() ;
            callServer(url,"json",data,onSalesQuotationDocumentResponse,null) ;
        }
    });
}

function cancelSalesQuotationDocs() {
    $('#salesquotation_docs_upload').html("");
    return false;
}

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

function openSubmitModal() {
    Swal.fire({
        title: "Submit (Approval) Sales Quotation",
        text: "If you change any data, make sure to save it first before continue it. Continue?'",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Continue",
        cancelButtonText: "Back",
        confirmButtonColor: '#2754e6',
    }).then(function(result) {
        if (result.value) {
            $('#submitSalesQuotationModal').modal('show');
            var pdf_filename = $('#txtSalesQuotationTitle').val()+$('#txtSalesQuotationNumber').val()+".pdf";
            $('#btnSubmitSalesQuotationPreview').html(pdf_filename);
            var id = $('#txtSalesQuotationID').val();
            addSalesQuotationSubmitDocsView(id,this);
        }
    });
}
function addSalesQuotationSubmitDocsView(id, obj) {
    var data  = { "type": "C_SALES_QUOTATION_SUBMIT_ATTACH_VIEW", "id" : id } ;
    var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + "C_SALES_QUOTATION_SUBMIT_ATTACH_VIEW" + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}
function submitSalesQuotation() {
    if($('#cobSalesQuotationApprover').val() == "" && $('#salesQuotationSubmitTo').val() == ""){
        Swal.fire("System Warning", "Approver and Email cannot be blank.", "warning");
        return;
    } else {
        var data = { 
            "type"          : "SEND_SALES_QUOTATION_SUBMIT",
            "id"            : $('#txtSalesQuotationID').val(),
            "approver"      : $('#cobSalesQuotationApprover').val(),
            "to_email"      : $('#salesQuotationSubmitTo').val(),
            "contact"       : "",
            "cc_email"      : $('#salesQuotationSubmitCC').val(),
            "remarks"       : $('#salesQuotationSubmitRemarks').val(),
            "attachments"   : getAttachmentList(),
        };
        var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onSalesQuotationResponse,sales_quotation_obj) ;
    }
}

function getAttachmentList() {
    var lists = [];
    $('#salesquotation_submit_approval_docs_list tr').each(function() {
        var attach_name = $(this).find("td:eq(0)").html();
        if(attach_name != null && attach_name != undefined)
            lists.push(attach_name);
    });

    return JSON.stringify(lists);
}

function populateUserEmail() {
    $('#cobSalesQuotationApproverEmail').val($('#cobSalesQuotationApprover').val());
    $('#salesQuotationSubmitTo').val($('#cobSalesQuotationApproverEmail option:selected').text());
}

function closedSalesQuotation() {
    Swal.fire({
        title: "Close Quotation",
        text: "Are you sure you want to close the quotation?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        confirmButtonColor: '#2754e6',
    }).then(function(result) {
        if (result.value) {
            var data = { 
                "id"            : $('#txtSalesQuotationID').val(),
                "type"          : C_SALES_QUOTATION_CLOSED,
                };
            var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
            callServer(url,"json",data,onSalesQuotationResponse,sales_quotation_obj) ;
        }
    });
    
}

//approval
function filterSalesQuotationApprovalList() {
    showProgress("Loading Sales Quotation Approval List" ) ;
    
    var data = { "type": C_SALES_QUOTATION_APPROVAL_FILTER, } ;
    var url  = "index.pzx?c=" + sales_quotation_url + "&t=" + C_SALES_QUOTATION_APPROVAL_FILTER  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onResponseSalesQuotationApproval,null) ;
}
function viewApprovalSalesQuotation(id) {
    screen_index++;
    var data  = { "type": C_SALES_QUOTATION_APPROVAL_VIEW, "id" : id, "index":screen_index } ;
    var url   = "index.pzx?c=" + sales_quotation_url + "&t=" + C_SALES_QUOTATION_APPROVAL_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onSalesQuotationResponse,null) ;
}
function openApprovalModal(id, quot_number) {
    clearSalesQuotationApproval();    
    $('#approvalSalesQuotationModal').modal('show');
    $('#txtSalesQuotationIdApproval').val(id);
    $('#txtSalesQuotationNumberApproval').val(quot_number);
    $('#btnConfirmApprovalSalesQuotation').attr('onclick','javascript:confirmApprovalSalesQuotation('+id+');');
}
function changedApprovalStatus(obj) {
    if($(obj).val() == 7) {
        $('#txtSalesQuotationApprovalReason').focus();
        $('#txtSalesQuotationApprovalReason').prop("disabled", false);
    } else {
        $('#txtSalesQuotationApprovalReason').val('');
        $('#txtSalesQuotationApprovalReason').prop("disabled", true);
    }
}
function confirmApprovalSalesQuotation(id) {
    if(validateApprovalSalesQuotation()) {
        var data = { 
            "type"              : C_SALES_QUOTATION_APPROVAL_CONFIRM,
            "id"                : id,
            "approval_status"   : $('#cobSalesQuotationApprovalStatus').val(),
            "approval_reason"   : $('#txtSalesQuotationApprovalReason').val(),
            };
        var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onResponseSalesQuotationApproval,null) ;
    }
}

function validateApprovalSalesQuotation() {
    if($('#cobSalesQuotationApprovalStatus').val() == ""){
        Swal.fire({
            title:"Warning",
            text: "Please select approval action.",
            type: "warning"
        });       
        return false;
    }
    if($('#txtSalesQuotationApprovalReason').val() == ""){
        Swal.fire({
            title:"Warning",
            text: "Reason cannot be blank.",
            type: "warning"
        });       
        return false;
    }
    return true;
}

//update view detail
function updateViewDetail(id) {    
    var data = { 
        "type"  : "C_UPDATE_VIEW_DETAIL",
        "id"    : id,
    };
    var url = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onResponseSalesQuotationApproval,null) ;
}

function clearSalesQuotationApproval(){
    $('#cobSalesQuotationApprovalStatus').val('');
    $('#txtSalesQuotationApprovalReason').val('');
    $('#txtSalesQuotationIdApproval').val('');
    $('#txtSalesQuotationNumberApproval').val('');
    $('#btnConfirmApprovalSalesQuotation').attr('onclick','javascript:confirmApprovalSalesQuotation(0);');
}

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

    if(resp.type == C_SALES_QUOTATION_APPROVAL_FILTER) {
        $('#sales-quotation-approval-list-table').html('');
        $('#sales-quotation-approval-list-table').append(resp.data.htmlStr);
    } else if(resp.type == C_SALES_QUOTATION_APPROVAL_CONFIRM) {
        Swal.fire("Success", resp.mesg, "success");
        $('#approvalSalesQuotationModal').modal('hide');
        // $('.modal-backdrop').remove();
        prevscreen();
        filterSalesQuotationApprovalList();
        $('#pendingApprovalNoTop').html(resp.data);
        $('#pendingApprovalNoBottom').html(resp.data);
    } else if(resp.type == "C_UPDATE_VIEW_DETAIL") {
        $('#pendingApprovalNoTop').html(resp.data);
        $('#pendingApprovalNoBottom').html(resp.data);
    } 
}

function updateExpected() {
    showProgress("Save Details" ) ;    
    if(validateRecord()) {
        var data = {
            "type"              : C_SALES_QUOTATION_UPDATE_EXPECTED,
            "id"                : $('#txtSalesQuotationID').val(), 
            "bu_id"             : $('#cobSalesQuotationBU').val(),
            "exp_accept_date"   : $('#txtSalesQuotationExpectedAcceptDate').val(),
            "exp_pay_date"      : $('#txtSalesQuotationExpectedPayDate').val(),
            "percentage_payment"    : $('#txtSalesQuotationPercentagePayment').val(),
        };
        var url  = "index.pzx?c=" + sales_quotation_url + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onSalesQuotationResponse,null) ;
    }
}