var C_DELETE_CONTACT_CUSTOMER   = "77003";
var C_CUSTOMER_CONTACT_FILTERS  = "77004";
var C_DELETE_CUSTOMER_DELIVERY  = "77005";
var C_CUSTOMER_DELIVERY_FILTERS = "77006";

var cust_contact_idx = 0;
var cust_branch_idx  = 0;
var cust_policy_idx  = 0;
var cust_software_idx  = 0;


function cancelCustomerEntry() {
    prevscreen('Customer');
    customerFilter();
}

function addCustomer() {
    saveCustomerEntry(C_ADD);
}
function updateCustomer() {
    saveCustomerEntry(C_UPDATE);
}

function saveCustomerEntry(type) {
    LoadingScreen("show");
    if (validateCustomerEntry()) {
        var data = {
            "type"               : type,
            //general
            "id"                 : $('#txtCustomerID').val(),
            "code"               : $('#txtCustomerCode').val(),
            "active"             : ($('#chkCustomerActive').is(':checked') ? '1' : '0'),
            "name"               : $('#txtCustomerName').val(),
            "company_reg_no"     : $('#txtCustomerCompanyRegNo').val(),
            "billing_cycle"      : $('#txtCustomerBillingCycle').val(),
            "account"            : $('#txtCustomerAccount').val(),
            "address"            : $('#txtCustomerAddress').val(),
            "remarks"            : $('#txtCustomerRemarks').val(),
            "industry"           : $('#txtCustomerIndustry').val(),
            "business_sector"    : $('#txtCustomerBusinessSector').val(),
            "no_people"          : $('#txtCustomerNoPeople').val(),
            "sales_turn_over"    : $('#txtCustomerSalesTurnOver').val(),
            "telephone"          : $('#txtCustomerCompanyTelephone').val(),

            "sunsystem_ver"      : $('#txtCustomerSunsystemVersion').val(),
            "mssql_ver"          : $('#txtCustomerMSSQLVersion').val(),
            "qa_ver"             : $('#txtCustomerQAVersion').val(),
            "windows_server_ver" : $('#txtCustomerWindowsServerVersion').val(),
            "software_info"      : $('#txtCustomerSoftwareInfo').val(),
            "supporting_partner" : $('#txtCustomerSupportingPartner').val(),
            "product_conver"     : $('#txtCustomerProductConversation').val(),
            "company_policy"     : $('#txtCustomerCompanyPolicy').val(),
            
            "pri_remote_access"  : $('#cobCustomerPrimaryRemoteAccess').val(),
            "pri_video_mesg"     : $('#cobCustomerPrimaryVideoMessage').val(),
            "sec_remote_access"  : $('#cobCustomerSecondaryRemoteAccess').val(),
            "sec_video_mesg"     : $('#cobCustomerSecondaryVideoMessage').val(),

            "new_contact_list"   : getCustomerNewContacts(),
            "new_branch_list"    : getCustomerNewBranch(),
            "new_policy_list"    : getCustomerNewPolicy(),
            "new_software_list"  : getCustomerNewSoftware(),
            "exist_contact_list" : getCustomerContacts(),
            "exist_branch_list"  : getCustomerBranch(),
            "exist_policy_list"  : getCustomerPolicy(),
            "exist_software_list": getCustomerSoftware(),
        };

        var url = "index.pzx?c=" + customer_url + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseCustomerEntry, null);
        return false;
    }else{
        LoadingScreen("hide");
    }
}

function validateCustomerEntry() {
    if ($('#txtCustomerCode').blank()) {
        swal.fire("Warning","Customer Code cannot be blank","warning");
        return false;
    }
    
    if ($('#txtCustomerName').blank()) {
        swal.fire("Warning","Customer Name cannot be blank","warning");
        return false;
    }

    return true;
}

//Contact
//====================================================
function showCustomerContact(contact_line_id){
    $('#btnCustomerContact').attr('onclick', 'saveCustomerContact('+contact_line_id+')');

    $('#txtCustomerContactCounter').val(contact_line_id);
    $('#txtCustomerContactFullName').val($('#cust_full_name' + contact_line_id).text());
    $('#txtCustomerContactPreferredName').val($('#cust_prefer_name' + contact_line_id).text());
    $('#txtCustomerContactDesignation').val($('#cust_designation' + contact_line_id).text());
    $('#cobCustomerContactSalutation').val($('#cust_salutation' + contact_line_id).html());
    $('#txtCustomerContactJobDescription').val($('#cust_job_desc' + contact_line_id).text());
    $('#txtCustomerContactDepartment').val($('#cust_dept' + contact_line_id).text());
    $('#cobCustomerContactDepartmentGroup').val($('#cust_dept_group_id' + contact_line_id).html());
    $('#txtCustomerContactReportTo').val($('#cust_report_to' + contact_line_id).text());
    $('#cobCustomerContactPosition').val($('#cust_position' + contact_line_id).html());
    $('#cobCustomerContactPosition').trigger('change');
    $('#chkCustomerContactActive').val($('#cust_contact_status' + contact_line_id).html());

    $('#txtCustomerContactEmail').val($('#cust_email' + contact_line_id).html());
    $('#txtCustomerContactTelephone').val($('#cust_telephone' + contact_line_id).html());
    $('#txtCustomerContactMobile').val($('#cust_mobile' + contact_line_id).html());
    $('#txtCustomerContactCommunicationPreference').val($('#cust_commun_prefer' + contact_line_id).text());
    $('#txtCustomerContactHobbies').val($('#cust_hobbies' + contact_line_id).text());
    $('#txtCustomerContactCharacter').val($('#cust_character' + contact_line_id).text());

    $('#txtCustomerContactPriority').val($('#cust_priority' + contact_line_id).html());
    $('#chkCustomerContacteSupportFin').val($('#cust_esupport_finance' + contact_line_id).html());
    $('#chkCustomerContacteSupportIT').val($('#cust_esupport_it' + contact_line_id).html());
    $('#chkCustomerContacteSupportProject').val($('#cust_esupport_project' + contact_line_id).html());
    $('#chkCustomerContacteSupportManagement').val($('#cust_esupport_management' + contact_line_id).html());

    if($('#cust_contact_status' + contact_line_id).html() == 1 ){
        $('#chkCustomerContactActive').prop('checked', true);
    }else{
        $('#chkCustomerContactActive').prop('checked', false);
    }
    if($('#cust_esupport_finance' + contact_line_id).html() == 1 ){
        $('#chkCustomerContacteSupportFin').prop('checked', true);
    }else{
        $('#chkCustomerContacteSupportFin').prop('checked', false);
    }
    if($('#cust_esupport_it' + contact_line_id).html() == 1 ){
        $('#chkCustomerContacteSupportIT').prop('checked', true);
    }else{
        $('#chkCustomerContacteSupportIT').prop('checked', false);
    }
    if($('#cust_esupport_project' + contact_line_id).html() == 1 ){
        $('#chkCustomerContacteSupportProject').prop('checked', true);
    }else{
        $('#chkCustomerContacteSupportProject').prop('checked', false);
    }
    if($('#cust_esupport_management' + contact_line_id).html() == 1 ){
        $('#chkCustomerContacteSupportManagement').prop('checked', true);
    }else{
        $('#chkCustomerContacteSupportManagement').prop('checked', false);
    }
}

function saveCustomerContact(contact_line_id){
    var contact_tr                  = $('#customer-contact-table-body tr');
    var total_eSupport_finance      = 0;
    var total_eSupport_it           = 0;
    var total_eSupport_project      = 0;
    var total_eSupport_management   = 0;

    var contact_eSupport_finance    = "";
    var contact_eSupport_it         = "";
    var contact_eSupport_project    = "";
    var contact_eSupport_management = "";

    contact_tr.each(function () {
        var idx = $(this).find(".counter").html();
        if(idx != $('#txtCustomerContactCounter').val()){   
            if($('#cust_esupport_finance' + idx).html() == 1){
                total_eSupport_finance++;
                contact_eSupport_finance += (contact_eSupport_finance == "") ? "<span style='font-weight: bold;'>Finance</span>: " + $('#cust_prefer_name' + idx).html() : ", " + $('#cust_prefer_name' + idx).html();
            }
            if($('#cust_esupport_it' + idx).html() == 1){
                total_eSupport_it++;
                contact_eSupport_it += (contact_eSupport_it == "") ? "<span style='font-weight: bold;'>IT</span>: " + $('#cust_prefer_name' + idx).html() : ", " + $('#cust_prefer_name' + idx).html();
            }
            if($('#cust_esupport_project' + idx).html() == 1){
                total_eSupport_project++;
                contact_eSupport_project += (contact_eSupport_project == "") ? "<span style='font-weight: bold;'>Project Manager</span>: " + $('#cust_prefer_name' + idx).html() : ", " + $('#cust_prefer_name' + idx).html();
            }
            if($('#cust_esupport_management' + idx).html() == 1){
                total_eSupport_management++;
                contact_eSupport_management += (contact_eSupport_management == "") ? "<span style='font-weight: bold;'>Management</span>: " + $('#cust_prefer_name' + idx).html() : ", " + $('#cust_prefer_name' + idx).html();
            }
        }
    });

    if($('#chkCustomerContacteSupportFin').is(':checked')){
        total_eSupport_finance++;
    }
    if($('#chkCustomerContacteSupportIT').is(':checked')){
        total_eSupport_it++;
    }
    if($('#chkCustomerContacteSupportProject').is(':checked')){
        total_eSupport_project++;
    }
    if($('#chkCustomerContacteSupportManagement').is(':checked')){
        total_eSupport_management++;
    }

    if(
        total_eSupport_finance > 2 || 
        total_eSupport_it > 2 || 
        total_eSupport_project > 2 ||
        total_eSupport_management > 2
    ){
        Swal.fire({
            title   : "Warning", 
            html    : "eSupport Primary Contact Department below has exceeded maximum number of 2 contacts allowed.<br><br>" + 
                        contact_eSupport_finance + "<br>" +
                        contact_eSupport_it + "<br>" +
                        contact_eSupport_project + "<br>" +
                        contact_eSupport_management + "<br>", 
            icon    :"warning"
        });
        return;
    }
    var full_name           = $('#txtCustomerContactFullName').val();
    var prefer_name         = $('#txtCustomerContactPreferredName').val();
    var designation         = $('#txtCustomerContactDesignation').val();
    var salutation          = $('#cobCustomerContactSalutation').val();
    var job_desc            = $('#txtCustomerContactJobDescription').val();
    var dept                = $('#txtCustomerContactDepartment').val();
    var dept_group_id       = $('#cobCustomerContactDepartmentGroup').val();
    var report_to           = $('#txtCustomerContactReportTo').val();
    var position            = $('#cobCustomerContactPosition').val();
    var contact_status      = ($('#chkCustomerContactActive').is(':checked') ? 'Active' : 'Inactive');
    var status              = $('#chkCustomerContactActive').is(':checked') ? '1' : '0';
    var email               = $('#txtCustomerContactEmail').val();
    var telephone           = $('#txtCustomerContactTelephone').val();
    var mobile              = $('#txtCustomerContactMobile').val();
    var commun_prefer       = $('#txtCustomerContactCommunicationPreference').val();
    var hobbies             = $('#txtCustomerContactHobbies').val();
    var character           = $('#txtCustomerContactCharacter').val();
    var priority            = $('#txtCustomerContactPriority').val();
    var esupport_finance    = ($('#chkCustomerContacteSupportFin').is(':checked') ? '1' : '0');
    var esupport_it         = ($('#chkCustomerContacteSupportIT').is(':checked') ? '1' : '0');
    var esupport_project    = ($('#chkCustomerContacteSupportProject').is(':checked') ? '1' : '0');
    var esupport_management = ($('#chkCustomerContacteSupportManagement').is(':checked') ? '1' : '0');

    if(full_name == ""){
        swal.fire("Warning", "Name cannot be blank", "warning");
    }else{
        if(contact_line_id == 'newline'){
            cust_contact_idx++;
            var contact_newline = "<tr id='lineContact"+cust_contact_idx+"' class='new_contact'>"+
                                    "<td id='line_num"+cust_contact_idx+"' class='counter' style='display:none;'>"+cust_contact_idx+"</td>"+
                                    "<td style='padding: 5px !important;' id='cust_prefer_name"+cust_contact_idx+"'>"+prefer_name+"</td>"+
                                    "<td style='padding: 5px !important;' id='cust_dept"+cust_contact_idx+"'>"+dept+"</td>"+
                                    "<td style='padding: 5px !important;' id='cust_email"+cust_contact_idx+"'>"+email+"</td>"+
                                    "<td style='padding: 5px !important;' id='cust_telephone"+cust_contact_idx+"'>"+telephone+"</td>"+
                                    "<td style='padding: 5px !important;' id='cust_mobile"+cust_contact_idx+"'>"+mobile+"</td>"+
                                    "<td style='padding: 5px !important;' id='cust_priority"+cust_contact_idx+"'>"+priority+"</td>"+
                                    "<td style='padding: 5px !important; text-align:center !important;' id='cust_contact_status_desc"+cust_contact_idx+"'>"+contact_status+"</td>"+
                                    "<td style='text-align:center !important;'>"+
                                    "<button onclick='deleteCustomerContact("+cust_contact_idx+")' class='btn btn-danger btn-sm btn-icon btn-icon-md'><i class='fa fa-trash-o'></i></button>"+
                                    "</td>"+
                                    "<td id='cust_dept_group_id"+cust_contact_idx+"' style='display:none'>"+dept_group_id+"</td>"+
                                    "<td id='cust_contact_status"+cust_contact_idx+"' style='display: none;'>"+status+"</td>"+
                                    "<td id='cust_full_name"+cust_contact_idx+"' style='display: none;'>"+full_name+"</td>"+
                                    "<td id='cust_designation"+cust_contact_idx+"' style='display: none;'>"+designation+"</td>"+
                                    "<td id='cust_salutation"+cust_contact_idx+"' style='display: none;'>"+salutation+"</td>"+
                                    "<td id='cust_job_desc"+cust_contact_idx+"' style='display: none;'>"+job_desc+"</td>"+
                                    "<td id='cust_report_to"+cust_contact_idx+"' style='display: none;'>"+report_to+"</td>"+
                                    "<td id='cust_position"+cust_contact_idx+"' style='display: none;'>"+position+"</td>"+
                                    "<td id='cust_commun_prefer"+cust_contact_idx+"' style='display: none;'>"+commun_prefer+"</td>"+
                                    "<td id='cust_hobbies"+cust_contact_idx+"' style='display: none;'>"+hobbies+"</td>"+
                                    "<td id='cust_character"+cust_contact_idx+"' style='display: none;'>"+character+"</td>"+
                                    "<td id='cust_priority"+cust_contact_idx+"' style='display: none;'>"+priority+"</td>"+
                                    "<td id='cust_esupport_finance"+cust_contact_idx+"' style='display: none;'>"+esupport_finance+"</td>"+
                                    "<td id='cust_esupport_it"+cust_contact_idx+"' style='display: none;'>"+esupport_it+"</td>"+
                                    "<td id='cust_esupport_project"+cust_contact_idx+"' style='display: none;'>"+esupport_project+"</td>"+
                                    "<td id='cust_esupport_management"+cust_contact_idx+"' style='display: none;'>"+esupport_management+"</td>"+
                                "</tr>";
            $('#customer-contact-table-body').append(contact_newline);
            $('#customer-contact-table-body tr').click(function() {
                showCustomerContact($(this).find('td').eq(0).html());
                $(this).addClass('highlight').siblings().removeClass('highlight');
            });
            clearCustomerContact();
        }else{
            $('#cust_prefer_name'+contact_line_id).html(prefer_name);
            $('#cust_dept'+contact_line_id).html(dept);
            $('#cust_dept_group_id'+contact_line_id).html(dept_group_id);
            $('#cust_email'+contact_line_id).html(email);
            $('#cust_telephone'+contact_line_id).html(telephone);
            $('#cust_mobile'+contact_line_id).html(mobile);
            $('#cust_full_name'+contact_line_id).html(full_name);
            $('#cust_designation'+contact_line_id).html(designation); 
            $('#cust_salutation'+contact_line_id).html(salutation);
            $('#cust_job_desc'+contact_line_id).html(job_desc);
            $('#cust_report_to'+contact_line_id).html(report_to); 
            $('#cust_position'+contact_line_id).html(position);
            $('#cust_commun_prefer'+contact_line_id).html(commun_prefer);
            $('#cust_hobbies'+contact_line_id).html(hobbies); 
            $('#cust_character'+contact_line_id).html(character);
            $('#cust_priority'+contact_line_id).html(priority);
            $('#cust_contact_status'+contact_line_id).html(status);
            $('#cust_esupport_finance'+contact_line_id).html(esupport_finance);
            $('#cust_esupport_it'+contact_line_id).html(esupport_it);
            $('#cust_esupport_project'+contact_line_id).html(esupport_project);
            $('#cust_esupport_management'+contact_line_id).html(esupport_management);
            $('#cust_contact_status_desc'+contact_line_id).html(contact_status);
            
            clearCustomerContact();
        }
        $('.btnSaveCustomer').first().click();
    }
}

function validateCustomerContact(){
    if($('#txtCustomerContactFullName').blank()){}
}

function clearCustomerContact(){
    $('#txtCustomerContactCounter').val('');
    $('#txtCustomerContactFullName').val('');    
    $('#cobCustomerContactSalutation').val(0);
    $('#txtCustomerContactReportTo').val('');
    $('#txtCustomerContactPreferredName').val('');
    $('#txtCustomerContactJobDescription').val('');
    $('#cobCustomerContactPosition').val(0);
    $('#txtCustomerContactDesignation').val('');
    $('#txtCustomerContactDepartment').val('');
    $('#cobCustomerContactDepartmentGroup').val(0);
    $('#chkCustomerContactActive').prop('checked', true);
    $('#txtCustomerContactEmail').val('');
    $('#txtCustomerContactCommunicationPreference').val('');
    $('#txtCustomerContactPriority').val(0);
    $('#txtCustomerContactTelephone').val('');
    $('#txtCustomerContactMobile').val('');
    $('#txtCustomerContactHobbies').val('');
    $('#chkCustomerContacteSupportFin').prop('checked', false);
    $('#chkCustomerContacteSupportIT').prop('checked', false);
    $('#chkCustomerContacteSupportProject').prop('checked', false);
    $('#chkCustomerContacteSupportManagement').prop('checked', false);
    $('#txtCustomerContactCharacter').val('');

    $('#btnCustomerContact').attr('onclick', 'saveCustomerContact(\"newline\")');
    $('#customer-contact-table-body .highlight').removeClass('highlight');
}

function deleteCustomerContact(contact_line_id){
    $('#lineContact' + contact_line_id).remove();
}


function deleteCustomerContactByID(id){
    Swal.fire({
        title: 'Are you sure?',
        text: "This Contact will be permanently deleted!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            LoadingScreen("show");
            data = {
                "type"          : "C_DELETE_CONTACT",
                "contact_id"    : id,
                "cust_id"       : $('#txtCustomerID').val()
            };
            var url = "index.pzx?c=" + customer_url + "&d=" + new Date().getTime();
            callServer(url, "json", data, onResponseCustomerEntry, null);
        }
    });
}

function getCustomerContacts() {
    var arrays = [];
    var data = {};
    var contact_tr = $('#customer-contact-table-body tr.existing_contact');
    contact_tr.each(function () {
        var idx = $(this).find(".counter").html();
        data = {
            "id"                    : $('#cust_id' + idx).html(),
            "full_name"             : $('#cust_full_name' + idx).text(),
            "prefer_name"           : $('#cust_prefer_name' + idx).text(),
            "designation"           : $('#cust_designation' + idx).text(),
            "salutation"            : $('#cust_salutation' + idx).html(),
            "job_desc"              : $('#cust_job_desc' + idx).text(),
            "dept"                  : $('#cust_dept' + idx).text(),
            "dept_group_id"         : $('#cust_dept_group_id' + idx).html(),
            "report_to"             : $('#cust_report_to' + idx).text(), 
            "position"              : $('#cust_position' + idx).html(),
            "contact_status"        : $('#cust_contact_status' + idx).html(),

            "email"                 : $('#cust_email' + idx).html(),
            "telephone"             : $('#cust_telephone' + idx).html(),
            "mobile"                : $('#cust_mobile' + idx).html(),
            "commun_prefer"         : $('#cust_commun_prefer' + idx).text(),
            "hobbies"               : $('#cust_hobbies' + idx).text(),
            "character"             : $('#cust_character' + idx).text(),
            "priority"              : $('#cust_priority' + idx).html(),
            "esupport_finance"      : $('#cust_esupport_finance' + idx).html(),
            "esupport_it"           : $('#cust_esupport_it' + idx).html(),
            "esupport_project"      : $('#cust_esupport_project' + idx).html(),
            "esupport_management"   : $('#cust_esupport_management' + idx).html(),
        };
        
        arrays.push(data);
    });
    return arrays;
}

function getCustomerNewContacts() {
    var arrays = [];
    var data = {};
    var contact_tr = $('#customer-contact-table-body tr.new_contact');
    contact_tr.each(function () {
        var idx = $(this).find(".counter").html();
        data = {            
            "full_name"             : $('#cust_full_name' + idx).text(),
            "prefer_name"           : $('#cust_prefer_name' + idx).text(),
            "designation"           : $('#cust_designation' + idx).text(),
            "salutation"            : $('#cust_salutation' + idx).html(),
            "job_desc"              : $('#cust_job_desc' + idx).text(),
            "dept"                  : $('#cust_dept' + idx).text(),
            "dept_group_id"         : $('#cust_dept_group_id' + idx).html(),
            "contact_status"        : $('#cust_contact_status' + idx).html(),
            "report_to"             : $('#cust_report_to' + idx).text(),
            "position"              : $('#cust_position' + idx).html(),
            "email"                 : $('#cust_email' + idx).html(),
            "telephone"             : $('#cust_telephone' + idx).html(),
            "mobile"                : $('#cust_mobile' + idx).html(),
            "commun_prefer"         : $('#cust_commun_prefer' + idx).text(),
            "hobbies"               : $('#cust_hobbies' + idx).text(),
            "character"             : $('#cust_character' + idx).text(),
            "priority"              : $('#cust_priority' + idx).html(),
            "esupport_finance"      : $('#cust_esupport_finance' + idx).html(),
            "esupport_it"           : $('#cust_esupport_it' + idx).html(),
            "esupport_project"      : $('#cust_esupport_project' + idx).html(),
            "esupport_management"   : $('#cust_esupport_management' + idx).html(),
        };
        
        arrays.push(data);
    });
    return arrays;
}

//====================================================

//Branch
//====================================================
function showCustomerBranch(branch_line_id){
    $('#btnCustomerBranch').attr('onclick', 'saveCustomerBranch('+branch_line_id+')');

    $('#txtCustomerBranchCode').val($('#cust_branch_code' + branch_line_id).html());
    $('#txtCustomerBranchName').val($('#cust_branch_name' + branch_line_id).html());
    $('#cobCustomerBranchType').val($('#cust_branch_type' + branch_line_id).html());
    $('#cobCustomerBranchType').trigger('change');
    $('#txtCustomerBranchAddress').val($('#cust_branch_add' + branch_line_id).html());
    $('#txtCustomerBranchWeb').val($('#cust_branch_web' + branch_line_id).html());
    $('#txtCustomerBranchEmail').val($('#cust_branch_email' + branch_line_id).html());
    $('#txtCustomerBranchTelephone').val($('#cust_branch_telephone' + branch_line_id).html());
    $('#cobCustomerBranchContact').val($('#cust_branch_contact' + branch_line_id).html());
    $('#cobCustomerBranchContact').trigger('change');
    $('#txtCustomerBranchFax').val($('#cust_branch_fax' + branch_line_id).html());
}

function saveCustomerBranch(branch_line_id){    
    if($('#cobCustomerBranchContact').blank() || $('#cobCustomerBranchContact').val()==0){
        swal.fire("Warning", "Branch Contact cannot be blank", "warning");
        return;
    }

    var code      = $('#txtCustomerBranchCode').val();
    var name      = $('#txtCustomerBranchName').val();
    var type      = $('#cobCustomerBranchType').val();
    var add       = $('#txtCustomerBranchAddress').val();
    var web       = $('#txtCustomerBranchWeb').val();
    var email     = $('#txtCustomerBranchEmail').val();
    var telephone = $('#txtCustomerBranchTelephone').val();
    var contact   = $('#cobCustomerBranchContact').val();
    var fax       = $('#txtCustomerBranchFax').val();
    
    if(name == ""){
        swal.fire("Warning", "Name cannot be blank", "warning");
    }else if(code == ""){
        swal.fire("Warning", "Code cannot be blank", "warning");
    }else{
        branch_type_desc = $("#cobCustomerBranchType option:selected").text();
        if($("#cobCustomerBranchType").val() == 0){
            branch_type_desc = '';
        }
        
        if(branch_line_id == 'newline'){
            cust_branch_idx++;
            var branch_newline = "<tr id='lineBranch"+cust_branch_idx+"' class='new_branch'>"+
                                    "<td id='line_num"+cust_branch_idx+"' class='counter' style='display:none;'>"+cust_branch_idx+"</td>"+
                                    "<td style='padding: 5px !important;' id='cust_branch_code"+cust_branch_idx+"'>"+code+"</td>"+
                                    "<td style='padding: 5px !important;' id='cust_branch_name"+cust_branch_idx+"'>"+name+"</td>"+
                                    "<td style='padding: 5px !important;' id='cust_branch_type_desc"+cust_branch_idx+"'>"+branch_type_desc+"</td>"+
                                    "<td style='padding: 5px !important; display:none;' id='cust_branch_type"+cust_branch_idx+"'>"+type+"</td>"+
                                    "<td style='padding: 5px !important;' id='cust_branch_telephone"+cust_branch_idx+"'>"+telephone+"</td>"+
                                    "<td style='padding: 5px !important;' id='cust_branch_email"+cust_branch_idx+"'>"+email+"</td>"+
                                    "<td style='text-align: center !important;'>"+
                                        "<button onclick='deleteCustomerBranch("+cust_branch_idx+")' class='btn btn-danger btn-sm btn-icon btn-icon-md'><i class='fa fa-trash-o'></i></button>"+
                                    "</td>"+
                                    "<td id='cust_branch_add"+cust_branch_idx+"' style='display: none;'>"+add+"</td>"+
                                    "<td id='cust_branch_web"+cust_branch_idx+"' style='display: none;'>"+web+"</td>"+
                                    "<td id='cust_branch_contact"+cust_branch_idx+"' style='display: none;'>"+contact+"</td>"+
                                    "<td id='cust_branch_fax"+cust_branch_idx+"' style='display: none;'>"+fax+"</td>"+
                                "</tr>";
            $('#customer-branch-table-body').append(branch_newline);
            $('#customer-branch-table-body tr').click(function() {
                showCustomerBranch($(this).find('td').eq(0).html());
                $(this).addClass('highlight').siblings().removeClass('highlight');
            });
            clearCustomerBranch()
        }else{
            $branch_type_desc = $("#cobCustomerBranchType option:selected").text();
            if($("#cobCustomerBranchType").val() == 0){
                $branch_type_desc = null;
            }

            $('#cust_branch_code'+branch_line_id).html(code);
            $('#cust_branch_name'+branch_line_id).html(name);
            $('#cust_branch_type_desc'+branch_line_id).html($branch_type_desc);
            $('#cust_branch_type'+branch_line_id).html(type);
            $('#cust_branch_telephone'+branch_line_id).html(telephone);
            $('#cust_branch_email'+branch_line_id).html(email);
            $('#cust_mobile'+branch_line_id).html(mobile);
            $('#cust_branch_add'+branch_line_id).html(add);
            $('#cust_branch_web'+branch_line_id).html(web);
            $('#cust_branch_contact'+branch_line_id).html(contact);
            $('#cust_branch_fax'+branch_line_id).html(fax);
            clearCustomerBranch();
        }
        $('.btnSaveCustomer').first().click();
    }
}

function clearCustomerBranch(){

    $('#txtCustomerBranchCode').val('');
    $('#txtCustomerBranchName').val('');
    $('#cobCustomerBranchType').val('');
    $('#txtCustomerBranchAddress').val('');
    $('#txtCustomerBranchWeb').val('');
    $('#txtCustomerBranchEmail').val('');
    $('#txtCustomerBranchTelephone').val('');
    $('#cobCustomerBranchContact').val(0);
    $('#txtCustomerBranchFax').val('');

    $('#btnCustomerBranch').attr('onclick', 'saveCustomerBranch(\"newline\")');
    $('#customer-branch-table-body .highlight').removeClass('highlight');
}

function deleteCustomerBranchByID(id){
    Swal.fire({
        title: 'Are you sure?',
        text: "This Branch will be permanently deleted!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            LoadingScreen("show");
            data = {
                "type"         : "C_DELETE_BRANCH",
                "branch_id"    : id,
                "cust_id"      : $('#txtCustomerID').val()
            };
            var url = "index.pzx?c=" + customer_url + "&d=" + new Date().getTime();
            callServer(url, "json", data, onResponseCustomerEntry, null);
        }
    });
}

function deleteCustomerBranch(branch_line_id){
    $('#lineBranch' + branch_line_id).remove();
}

function getCustomerNewBranch() {
    var arrays = [];
    var data = {};
    var branch_tr = $('#customer-branch-table-body tr.new_branch');
    branch_tr.each(function () {
        var idx = $(this).find(".counter").html();
        data = {            
            "code"          : $('#cust_branch_code'+idx).html(),
            "name"          : $('#cust_branch_name'+idx).html(),
            "branch_type"   : $('#cust_branch_type'+idx).html(),
            "telephone"     : $('#cust_branch_telephone'+idx).html(),
            "email"         : $('#cust_branch_email'+idx).html(),
            "mobile"        : $('#cust_mobile'+idx).html(),
            "add"          : $('#cust_branch_add'+idx).html(),
            "web"           : $('#cust_branch_web'+idx).html(),
            "contact"       : $('#cust_branch_contact'+idx).html(),
            "fax"           : $('#cust_branch_fax'+idx).html(),
        };
        
        arrays.push(data);
    });
    return arrays;
}

function getCustomerBranch() {
    var arrays = [];
    var data = {};
    var branch_tr = $('#customer-branch-table-body tr.existing_branch');
    branch_tr.each(function () {
        var idx = $(this).find(".counter").html();
        data = {
            "id"            : $('#cust_branch_id'+idx).html(),
            "code"          : $('#cust_branch_code'+idx).html(),
            "name"          : $('#cust_branch_name'+idx).html(),
            "branch_type"   : $('#cust_branch_type'+idx).html(),
            "telephone"     : $('#cust_branch_telephone'+idx).html(),
            "email"         : $('#cust_branch_email'+idx).html(),
            "mobile"        : $('#cust_mobile'+idx).html(),
            "add"           : $('#cust_branch_add'+idx).html(),
            "web"           : $('#cust_branch_web'+idx).html(),
            "contact"       : $('#cust_branch_contact'+idx).html(),
            "fax"           : $('#cust_branch_fax'+idx).html(),
        };
        
        arrays.push(data);
    });
    return arrays;
}

function updateBranchContactOption(){
    var contact_tr  = $('#customer-contact-table-body tr');
    var option      = "<option value='0'>--- Select one ---</option>";
    contact_tr.each(function () {
        var idx = $(this).find(".counter").html();
        var prefer_name = $('#cust_prefer_name' + idx).html();
        var id          = $('#cust_id' + idx).html();
        
        if(id == null || id == ''){
            option  += "<option value='"+prefer_name+"'>"+prefer_name+"</option>"
        }else{
            option  += "<option value='"+id+"'>"+prefer_name+"</option>"
        }
    });

    $('#cobCustomerBranchContact').html('');
    $('#cobCustomerBranchContact').html(option);
}
//====================================================

//Policy
//====================================================
function newCustomerPolicy(){    
    $('#customer-policy-table-body').append(
        '<tr id="policyLine'+cust_policy_idx+'" class="new_policy">' +
            '<td id="line_num'+cust_policy_idx+'" class="counter" style="display:none;">'+cust_policy_idx+'</td>'+
            '<td><input type="text" style="width: 100%" class="form-control" id="txtCustomerNewPolicyDesc'+cust_policy_idx+'"></td>'+
            '<td><input type="file" style="width: 100%; class="form-control" background-color: #eeeeee;" id="txtCustomerNewPolicyAttach'+cust_policy_idx+'" onchange="encodeImageFileAsURLCustomerPolicy('+cust_policy_idx+')"></td>'+
            '<td><button class="btn btn-danger btn-sm btn-icon btn-icon-md" type="button" id="btnDeletePolicy" onclick="deleteCustomerPolicy('+cust_policy_idx+');"><i class="fa fa-trash-o"></i></button></td>'+
            '<td style="display: none;"><textarea id="txtCustomerNewPolicyAttachmentFileBase64'+cust_policy_idx+'"></textarea></td>'+
            '<td style="display: none;" id="txtCustomerNewPolicyAttachmentFileExt'+cust_policy_idx+'"></td>'+
            '<td style="display: none;" id="txtCustomerNewPolicyAttachmentFilename'+cust_policy_idx+'"></td>'+
        '</tr>'
    )
    cust_policy_idx++;
}


function encodeImageFileAsURLCustomerPolicy(idx) {
    var filesSelected = document.getElementById("txtCustomerNewPolicyAttach" + idx).files;
	if (!hasExtensionCustomerPolicy("txtCustomerNewPolicyAttach" + idx, ['.jpg', '.jpeg', '.png','.pdf'])) {
		swal.fire('Warning', "The image format have to be in 'jpg', 'jpeg', 'png' , 'pdf", "warning");
		$("txtCustomerNewPolicyAttach" + idx).val("");
		return;
	}

    if (filesSelected.length > 0) {
       	var fileToLoad = filesSelected[0];
	   	var fileExt = getFileExtensionCustomerPolicy(filesSelected[0].name);
		  	
      	var fileReader = new FileReader();

      	fileReader.onload = function(fileLoadedEvent) {
			var srcData = fileLoadedEvent.target.result; // <--- data: base64

			$('#txtCustomerNewPolicyAttachmentFileBase64' + idx).html(srcData);
			$('#txtCustomerNewPolicyAttachmentFileExt' + idx).html(fileExt);
			$('#txtCustomerNewPolicyAttachmentFilename' + idx).html(filesSelected[0].name);
      	}
      fileReader.readAsDataURL(fileToLoad);
    }
}

function getCustomerNewPolicy() {
    var arrays = [];
    var data = {};
    var policy_tr = $('#customer-policy-table-body tr.new_policy');
    policy_tr.each(function () {
        var idx = $(this).find(".counter").html();

        data = {
            "desc"        : $('#txtCustomerNewPolicyDesc'+idx).val(),
            "base_64"     : $('#txtCustomerNewPolicyAttachmentFileBase64'+idx).val(),
            "ext"         : $('#txtCustomerNewPolicyAttachmentFileExt'+idx).html(),
            "filename"    : $('#txtCustomerNewPolicyAttachmentFilename'+idx).html(),
        };
        arrays.push(data);
    });
    return arrays;
}

function getCustomerPolicy() {
    var arrays = [];
    var data = {};
    var policy_tr = $('#customer-policy-table-body tr.existing_policy');
    policy_tr.each(function () {
        var idx = $(this).find(".counter").html();

        data = {
            "id"          : $('#txtCustomerPolicyId'+idx).val(),
            "desc"        : $('#txtCustomerPolicyDesc'+idx).val(),
        };
        arrays.push(data);
    });
    return arrays;
}

function getFileExtensionCustomerPolicy(filename){
	var ext = /^.+\.([^.]+)$/.exec(filename);
	return ext == null ? "" : ext[1];
}

function hasExtensionCustomerPolicy(inputID, exts) {
    var fileName = document.getElementById(inputID).value;
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName.toLowerCase());
}

function deleteCustomerPolicy(policy_line_id){
    $('#policyLine' + policy_line_id).remove();
}

function downloadCustomerPolicy(policy_line_id){
    var url = "index.pzx?c=" + customer_url + "&id=" + $('#txtCustomerPolicyId'+policy_line_id).val() + 
        "&t=" + "C_CUSTOMER_DOWNLOAD_POLICY"  + "&r=1";
    showReport(url) ;
}
//====================================================

//Software
//====================================================
function newCustomerSoftware(){    
    $('#customer-software-table-body').append(
        '<tr id="softwareLine'+cust_software_idx+'" class="new_software">' +
            '<td id="line_num'+cust_software_idx+'" class="counter" style="display:none;">'+cust_software_idx+'</td>'+
            '<td style="border-right: 1px solid #e0e0e0"><select id="cobCustomerNewSoftwareCode'+cust_software_idx+'" class="form-control" style="width: 100%">' + $('#cobCustomerSoftwareOption').html() +'</select></td>'+
            '<td style="border-right: 1px solid #e0e0e0"><input type="text" style="width: 100%" class="form-control" id="txtCustomerNewSoftwareVersion'+cust_software_idx+'"></td>'+
            '<td style="border-right: 1px solid #e0e0e0"><input type="number" style="width: 100%" class="form-control" id="txtCustomerNewSoftwareUser'+cust_software_idx+'"></td>'+
            '<td style="border-right: 1px solid #e0e0e0">' +
                '<select id="cobCustomerNewSoftwareType'+cust_software_idx+'" class="form-control" style="width: 100%">' +
                    '<option value="0">--- Select Type ---</option>' +
                    '<option value="1">Subscription</option>' +
                    '<option value="2">License</option>' +
                '</select>' +
            '</td>'+
            '<td style="border-right: 1px solid #e0e0e0"><input type="date" style="width: 100%" class="form-control" id="txtCustomerNewSoftwareLiveDate'+cust_software_idx+'"></td>'+
            '<td style="border-right: 1px solid #e0e0e0"><input type="date" style="width: 100%" class="form-control" id="txtCustomerNewSoftwareRenewDate'+cust_software_idx+'"></td>'+
            '<td><button class="btn btn-danger btn-sm btn-icon btn-icon-md" type="button" id="btnDeleteSoftware" onclick="deleteCustomerSoftware('+cust_software_idx+');"><i class="fa fa-trash-o"></i></button></td>'+
        '</tr>'
    )
    cust_software_idx++;
}

function getCustomerNewSoftware() {
    var arrays = [];
    var data = {};
    var software_tr = $('#customer-software-table-body tr.new_software');
    software_tr.each(function () {
        var idx = $(this).find(".counter").html();

        data = {
            "code"          : $('#cobCustomerNewSoftwareCode'+idx).val(),
            "version"       : $('#txtCustomerNewSoftwareVersion'+idx).val(),
            "user"          : $('#txtCustomerNewSoftwareUser'+idx).val(),
            "soft_type"     : $('#cobCustomerNewSoftwareType'+idx).val(),
            "live_date"     : $('#txtCustomerNewSoftwareLiveDate'+idx).val(),
            "renew_date"    : $('#txtCustomerNewSoftwareRenewDate'+idx).val(),
        };
        arrays.push(data);
    });
    return arrays;
}

function getCustomerSoftware() {
    var arrays = [];
    var data = {};
    var software_tr = $('#customer-software-table-body tr.existing_software');
    software_tr.each(function () {
        var idx = $(this).find(".counter").html();

        data = {
            "id"            : $('#txtCustomerSoftwareId'+idx).val(),
            "code"          : $('#cobCustomerSoftwareCode'+idx).val(),
            "version"       : $('#txtCustomerSoftwareVersion'+idx).val(),
            "user"          : $('#txtCustomerSoftwareUser'+idx).val(),
            "soft_type"     : $('#cobCustomerNewSoftwareType'+idx).val(),
            "live_date"     : $('#txtCustomerSoftwareLiveDate'+idx).val(),
            "renew_date"    : $('#txtCustomerSoftwareRenewDate'+idx).val(),
        };
        arrays.push(data);
    });
    return arrays;
}

function deleteCustomerSoftware(software_line_id){
    $('#softwareLine' + software_line_id).remove();
}

function getContactBranchList(id){
    LoadingScreen("show");
    data = {
            "type"  : "C_LATEST_CONTACT_BRANCH",
            "id"    : id,
        };
    var url = "index.pzx?c=" + customer_url + "&d=" + new Date().getTime();
    callServer(url, "json", data, onResponseCustomerEntry, null);
}

//====================================================

function onResponseCustomerEntry(obj, resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK) {
        swal.fire('Warning', resp.mesg, 'warning');
        getContactBranchList(resp.data.id);
        return;
    }

    if (resp.type == C_ADD) {
        swal.fire('Success', resp.mesg, 'success');
        $(".btnSaveCustomer").attr("onclick", "updateCustomer();");
        $("#txtCustomerID").val(resp.data.id);

        updateBranchContactOption();
        showPolicyList(resp.data.policy);
        getContactBranchList(resp.data.id)
    } 
    if (resp.type == C_UPDATE) {
        swal.fire('Success', resp.mesg, 'success');
        $(".btnSaveCustomer").attr("onclick", "updateCustomer();");
        updateBranchContactOption();
        showPolicyList(resp.data.policy);
        getContactBranchList(resp.data.id)
    }
    if(resp.type == "C_LATEST_CONTACT_BRANCH"){
        $('#customer-contact-table-body').html('');
        $('#customer-branch-table-body').html('');
        showContactList(resp.data.contact);
        showBranchList(resp.data.branch);
    }
    if(resp.type == "C_DELETE_CONTACT"){
        swal.fire('Success', resp.mesg, 'success');
        getContactBranchList(resp.data)
    }
    if(resp.type == "C_DELETE_BRANCH"){
        swal.fire('Success', resp.mesg, 'success');
        getContactBranchList(resp.data)
    }
}