var C_ADD_CUSTOMER_VIEW                 = "512";
var C_UPDATE_CUSTOMER_VIEW              = "513";
var C_DELETE_CUSTOMER                   = "514";
var C_CUSTOMER_FILTERS                  = "511";
var C_DELETE_CONTACT                    = "525";
var C_CONTACT_FILTERS                   = "526";
var C_PROJECT_FILTERS                   = "527";

var customer_obj                        = null;
var contact_obj                         = null;
var contact_idx                         = 0;

$(document).ready(function () {
});
/*function getCustomerAutoSearch(){
    var data = { "type": "C_SEARCH" } ;
    var url = "request.pzx?c=" + customer_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustomerAutoSearch,customer_obj) ;
}
function onCustomerAutoSearch(obj,resp) { 
    if (resp.status == C_OK) {
        if (resp.data != null || resp.data.length != 0 ) {
            var filteredBuilding = resp.data;

            $('#filterNameCustomer').autocomplete({
                source: filteredBuilding,
                minLength: 1,
                autoFocus: true
            });
        }
    }
}*/
function filterCustomer(){
    // screen_index++;
    var data = { 
            "type": C_CUSTOMER_FILTERS, 
            "status": 'all',
            "sorts": sorts,
            "index": screen_index,
        };
    var url  = "index.pzx?c=" + customer_url + "&t=" + C_CUSTOMER_FILTERS  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustomerResponse,null) ;
    return false;
}
function newCustomer() {
    screen_index++;
    var data = { "type": C_ADD_CUSTOMER_VIEW, "index": screen_index, } ;
    var url  = "index.pzx?c=" + customer_url + "&t=" + C_ADD_CUSTOMER_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustomerResponse,null) ;
}
function addCustomer() {
    saveCustomer(C_ADD);
}
function updateCustomer() {
    saveCustomer(C_UPDATE) ; 
}
function saveCustomer(type){
    if (validateCustomer()){
        var data = {        "type"              : type,
                            //general
                            "id"                : $('#txtCustomerID').val(),
                            "active"            : ($('#chkCustomerActive').is(':checked') ? '1' : '0'),
                            "name"              : $('#txtCustomerName').val(), 
                            "code"              : $('#txtCustomerCode').val(),
                            "telephone"         : $('#txtCustomerTelephone').val(),
                            "address1"          : $('#txtCustomerAddress1').val(),
                            "address2"          : $('#txtCustomerAddress2').val(),
                            "address3"          : $('#txtCustomerAddress3').val(),
                            "address4"          : $('#txtCustomerAddress4').val(),
                            "address5"          : $('#txtCustomerAddress5').val(),
                            "software"          : $('#txtCustomerSoftwareInfo').val(),
                            "billing_cycle"     : $('#txtCustomerBillingCycle').val(),
                            "remarks"           : $('#txtCustomerRemarks').val(),
                            //contact
                            "contacts"           : getContacts(),
                        };
        var url  = "index.pzx?c=" + customer_url + "&t=" + type  + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onCustomerResponse,customer_obj) ;
    } 
}
function getContacts(){
    var arrays = [];
    var data = {};
    var contact_tr = $('#contact-list-table tr');
    contact_tr.each(function() {
        var idx = $(this).attr('id');
        idx = idx.substring(idx.lastIndexOf('-')+1);
        if (idx != "filter") {
            data = {     
                "id"        :$('#txtcolcontactid'+idx).val()  ,
                "name"      :$('#txtcolcontactname'+idx).val()  ,
                "dept"      :$('#txtcolcontactdept'+idx).val()  ,
                "position"  :$('#txtcolcontactposition'+idx).val()  ,
                "email"     :$('#txtcolcontactemail'+idx).val()  ,
                "phone"     :$('#txtcolcontactphone'+idx).val()  ,
                "mobile"    :$('#txtcolcontactmobile'+idx).val()  ,  
                "reportto"  :$('#txtcolcontactreportto'+idx).val()  ,   
                "status"    :$('#txtcolcontactstatus'+idx).val()  ,  
               };
            
            arrays.push(data);
        }
    }); 
    console.log(arrays);
    // return JSON.stringify(arrays) ;
    return arrays;
}
function editCustomer(id, obj) {
    customer_obj = obj ;
    /**add index ++ here, so the index will be increase */
    screen_index++;
    var data  = { "type": C_UPDATE_CUSTOMER_VIEW, "id" : id, "sorts": sorts, "index": screen_index } ;
    var url   = "index.pzx?c=" + customer_url + "&t=" + C_UPDATE_CUSTOMER_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustomerResponse,customer_obj) ;
}
function deleteCustomer(id) {
    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) {
            var data = { 
                "type": C_DELETE_CUSTOMER,
                "id": id
            } ;
            var url = "index.pzx?c=" + customer_url + "&t=" + C_DELETE_CUSTOMER  + "&d=" + new Date().getTime() ; 
            callServer(url,"json",data,onCustomerResponse,null) ;
        }
    });
}
function onCustomerResponse(obj,resp){
    // console.log(resp.data);
    if (resp.status != C_OK ) {
        Swal.fire("Error",resp.mesg,"error");
        return false;
    }
    
    if (resp.type == C_ADD) {
        Swal.fire("Success",resp.mesg,"success");
        filterCustomer();
        prevscreen();
    }  else if (resp.type == C_UPDATE) {
        Swal.fire("Success",resp.mesg,"success");
        // editCustomer(resp.data.headerData.id,obj);
        filterCustomer();
        prevscreen();
    } else if (resp.type == C_DELETE_CUSTOMER) {
        Swal.fire("Success",resp.mesg,"success");
        filterCustomer();
    } else if (resp.type == C_ADD_CUSTOMER_VIEW) {
        showScreen(resp);
        $("#btnSaveCustomer").attr("onclick","addCustomer();");
        // $("#btnFilterContact").prop("disabled","disabled");
        // $("#btnNewContact").prop("disabled","disabled");
    }  else if (resp.type == C_UPDATE_CUSTOMER_VIEW) {
        if(resp.type == C_UPDATE_CUSTOMER_VIEW)
            showScreen(resp);
        
        if(resp.data.headerData.status == '1'){
            $('#chkCustomerActive').prop('checked', true);
        } else {
            $('#chkCustomerActive').prop('checked', false);
        }
        $("#btnSaveCustomer").attr("onclick","updateCustomer();");
        $('#txtCustomerID').val(resp.data.headerData.id) ;
        $('#txtCustomerCode').val(resp.data.headerData.code) ;
        $('#txtCustomerName').val(resp.data.headerData.name) ;
        $('#txtCustCode').val(resp.data.headerData.code) ;
        $('#txtCustName').val(resp.data.headerData.name) ;
        $('#txtCustomerTelephone').val(resp.data.headerData.telephone) ;
        $('#txtCustomerAddress1').val(resp.data.headerData.address1) ;
        $('#txtCustomerAddress2').val(resp.data.headerData.address2) ;
        $('#txtCustomerAddress3').val(resp.data.headerData.address3) ;
        $('#txtCustomerAddress4').val(resp.data.headerData.address4) ;
        $('#txtCustomerAddress5').val(resp.data.headerData.address5) ;
        $('#txtCustomerSoftwareInfo').val(resp.data.headerData.software) ; 
        $('#txtCustomerBillingCycle').val(resp.data.headerData.billing_cycle) ; 
        $('#txtCustomerRemarks').val(resp.data.headerData.remarks) ; 

        contact_idx = resp.data.contactIdx;
        var wrapper = $('#contact-row-filter');
        wrapper.nextAll().remove();
        wrapper.after(resp.data.htmlContact);

        var wrapperproj = $('#project-row-filter');
        wrapperproj.nextAll().remove();
        wrapperproj.after(resp.data.htmlProject);
    } else if(resp.type == C_CUSTOMER_FILTERS) {
        var wrapper = $('#customer-row-filter');
        wrapper.nextAll().remove();
        wrapper.after(resp.data);
    } else if(resp.type == C_DELETE_CONTACT) {
        filterContact();
    } else if(resp.type == C_CONTACT_FILTERS) {
        if($('#txtCustomerID').val() != "") {
            contact_idx = resp.data.contactIdx;
            var wrapper = $('#contact-row-filter');
            wrapper.nextAll().remove();
            wrapper.after(resp.data.htmlContact);
        }        
    } else if(resp.type == C_PROJECT_FILTERS) {
        var wrapperproj = $('#project-row-filter');
        wrapperproj.nextAll().remove();
        wrapperproj.after(resp.data.htmlProject);
    }
}
function validateCustomer(){    
    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;
}
function filterProject(){
    var data = { 
            "type": C_PROJECT_FILTERS,
            "id": $('#txtCustomerID').val(),
            "sorts": sorts,
        };
    var url  = "index.pzx?c=" + customer_url + "&t=" + C_PROJECT_FILTERS  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustomerResponse,null) ;
    return false;
}
function filterContact(){
    var data = { 
            "type": C_CONTACT_FILTERS,
            "cust_id": $('#txtCustomerID').val(),
            "sorts": sorts,
        };
    var url  = "index.pzx?c=" + customer_url + "&t=" + C_CONTACT_FILTERS  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustomerResponse,null) ;
    return false;
}
function newContact() {
    contact_idx++;
    // console.log(contact_idx);
    var newRow = "<tr data-row='contact-rows-"+contact_idx+"' id='contact-rows-"+contact_idx+"' class='dnd-moved kt-datatable__row' style='left: 0px;'> " +
                    "<td data-field='contactid' class='kt-datatable__cell' id='col_contactid"+contact_idx+"' style='display: none;'><input type='text' class='form-control' name='input_row' id='txtcolcontactid"+contact_idx+"' /></td> " +
                    "<td data-field='contactname' class='kt-datatable__cell' id='col_contactname"+contact_idx+"'><input type='text' class='form-control' name='input_row' id='txtcolcontactname"+contact_idx+"' /></td> " +
                    "<td data-field='contactdept' class='kt-datatable__cell' id='col_contactdept"+contact_idx+"'><input type='text' class='form-control' name='input_row' id='txtcolcontactdept"+contact_idx+"' /></td> " +
                    "<td data-field='contactposition' class='kt-datatable__cell' id='col_contactposition"+contact_idx+"'><input type='text' class='form-control' name='input_row' id='txtcolcontactposition"+contact_idx+"' /></td> " +
                    "<td data-field='contactemail' class='kt-datatable__cell' id='col_contactemail"+contact_idx+"'><input type='text' class='form-control' name='input_row' id='txtcolcontactemail"+contact_idx+"' /></td> " +
                    "<td data-field='contactphone' class='kt-datatable__cell' id='col_contactphone"+contact_idx+"'><input type='text' class='form-control' name='input_row' id='txtcolcontactphone"+contact_idx+"' /></td> " +
                    "<td data-field='contactmobile' class='kt-datatable__cell' id='col_contactmobile"+contact_idx+"'><input type='text' class='form-control' name='input_row' id='txtcolcontactmobile"+contact_idx+"' /></td> " +
                    "<td data-field='contactreportto' class='kt-datatable__cell' id='col_contactreportto"+contact_idx+"'><input type='text' class='form-control' name='input_row' id='txtcolcontactreportto"+contact_idx+"' /></td> " +
                    "<td data-field='contactstatus' class='kt-datatable__cell' id='col_contactstatus"+contact_idx+"'>" +
                    "<select class='form-control' name='input_row' id='txtcolcontactstatus"+contact_idx+"'>" +
                    "<option value='1'>Active</option>" +
                    "<option value='0'>Inactive</option>" +
                    "</select>" +
                    "</td> " +
                    "<td data-field='filter' class='kt-datatable__cell' style='width: 50px;' id='col_filter"+contact_idx+"'>" +
                    "<button type='button' class='btn btn-danger btn-sm btn-icon btn-icon-md' id='btnRemoveContact' onclick='removeContact("+contact_idx+");'><i class='fa fa-trash-alt'></i></button></td> " +
                "</tr>";
    $('#contact-list-table').append(newRow);
}
function removeContact(idx) {
    $("#contact-rows-"+idx).remove();
    if(idx == contact_idx)
        contact_idx--;
}
function deleteContact(id, obj) {
    Swal.fire({
        title: "Delete Confirmation",
        text: "Confirm you want to delete the record?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes",
        cancelButtonColor: '#d33',
    }).then(function(result) {
        if (result.value) {
            var data = { 
                "type": C_DELETE_CONTACT,
                "cust_id": $('#txtCustomerID').val(),
                "id": id,
            } ;
            // console.log(data);
            var url = "index.pzx?c=" + customer_url + "&t=" + C_DELETE_CONTACT  + "&d=" + new Date().getTime() ; 
            callServer(url,"json",data,onCustomerResponse,null) ;
        }
    });
}