var C_CUST_LOC_FILTER       = "1001";
var C_ADD_CUST_LOC_VIEW     = "1002";
var C_UPDATE_CUST_LOC_VIEW  = "1003";
var C_DELETE_CUST_LOC       = "1004";

var customerloc_obj = null ;
var m_asset_idx = 0;

function getCustLocationAutoSearch(){
    var data = { "type": "C_CUSTNAME_SEARCH" } ;
    var url = "request.pzx?c=" + customerloc_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustLocationAutoSearch,customerloc_obj) ;
}

function onCustLocationAutoSearch(obj,resp) { 
    if (resp.status == C_OK) {
        if (resp.data != null || resp.data.length != 0 ) {
            var filteredBuilding = resp.data;

            $('#filterCustomerName').autocomplete({
                source: filteredBuilding,
                minLength: 1,
                autoFocus: true
            });
        }
    }
}

function populateModel() {
    var brandId = $("#cobCustLocBrand").val();
    var data = { "type": C_GET + "_MODEL", "brandId" : brandId} ;
    var url = "request.pzx?c=" + customerloc_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustomerLocationResponse,customerloc_obj) ;
}

function showAddCustomerLocation(){
    showProgress("loading Customer Location" ) ;
    var data = { "type": C_ADD_CUST_LOC_VIEW} ;
    var url  = "index.pzx?c=" + customerloc_url + "&t=" + C_ADD_CUST_LOC_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustomerLocationResponse,null) ;
}

function filterCustomerLocation(){
    var data = { "type" : C_CUST_LOC_FILTER, 
                  'customer': $("#filterCustomerName").val()
                    };
    var url  = "index.pzx?c=" + customerloc_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustomerLocationResponse,null) ;
}

function addCustomerAsset() {
    if($('#cobCustLocSerialNumb').blank() || $('#cobCustLocProduct').val()==0 || $('#cobCustLocBrand').val()==0 || $('#cobCustLocModel').val()==0){
        showMessage('error', "Please fill all the asset first!", "Warning");
        return false;
    }

    m_asset_idx++;
    $('#customer-asset-table').append("<tr id='trCustomerAsset" + m_asset_idx + "'><td style='width:30px;display:none'>" +m_asset_idx+ "</td>" +
        "<td style='width:12.5%;display:none;'>" + $('#cobCustLocProduct :selected').val() + "</td>" +
        "<td style='width:12.5%;'>" + $('#cobCustLocProduct :selected').text() + "</td>" +
        "<td style='width:12.5%;display:none;'>" + $('#cobCustLocBrand :selected').val() + "</td>" +
        "<td style='width:12.5%;'>" + $('#cobCustLocBrand :selected').text() + "</td>" +
        "<td style='width:12.5%;display:none;'>" + $('#cobCustLocModel :selected').val() + "</td>" +
        "<td style='width:12.5%;'>" + $('#cobCustLocModel :selected').text() + "</td>" +
        "<td style='width:12.5%;'>" + $('#cobCustLocSerialNumb').val() + "</td>" +
        "<td style='width:7.5%;'>" + $('#txtCustLocWarrStart').val() + "</td>" +
        "<td style='width:7.5%;'>" + $('#txtCustLocWarrEnd').val() + "</td>" +
        "<td style='width:8%;'><input type='text' class='form-control txtExtCustLocWarr' id='txtExtCustLocWarr"+m_asset_idx+"' ></td>" +
        "<td style='width:8%;'><input type='text' class='form-control txtExtCustLocWarrEnd' id='txtExtCustLocWarrEnd"+m_asset_idx+"' ></td>" +
        "<td style='width:3%;'><input type='number' class='form-control txtCycle' id='txtCycle"+m_asset_idx+"' ></td>" +
        "<td style='width:3%;'></td>" +
        "<td style='text-align:center;'><a href='javascript:' onclick='removeCustomerAsset(" + m_asset_idx + ")'><span class='glyphicon glyphicon-trash'></span></a></td></tr>"); 
    clearCustomerAsset();

    $('.txtExtCustLocWarr').datepicker({
        format: "dd/mm/yyyy"
    });
    $('.txtExtCustLocWarr').on('changeDate', function(ev){
        $(this).datepicker('hide');
    });

    $('.txtExtCustLocWarrEnd').datepicker({
        format: "dd/mm/yyyy"
    });
    $('.txtExtCustLocWarrEnd').on('changeDate', function(ev){
        $(this).datepicker('hide');
    });
}

function clearCustomerAsset() {
    $('#txtCustLocRemarks').val('') ;
}

function removeCustomerAsset(idx) {
    $('#trCustomerAsset'+idx).remove() ;
}

function addCustomerLocation() {
    saveCustomerLocation(C_ADD);
}

function showEditCustomerLocation(id, obj) {
    customerloc_obj = obj ;
    showProgress("loading Customer Location" ) ;
    var data  = { "type": C_UPDATE_CUST_LOC_VIEW, "id" : id} ;
    var url   = "index.pzx?c=" + customerloc_url + "&t=" + C_UPDATE_CUST_LOC_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustomerLocationResponse,null) ;
}

function showCustomerAsset(lines) {
    if (lines == undefined || lines == null || lines == "") return ;
    
    var line = lines.split('|') ;
    var fld = "" ;
    m_asset_idx = 0 ;
    for (var i = 0 ; i < line.length ; i++) {
        if (line[i] != "") {
            fld = line[i].split('~') ;
            m_asset_idx++;
            $('#customer-asset-table').append("<tr id='trCustomerAsset" + m_asset_idx + "'><td style='width:30px;display:none'>" +m_asset_idx+ "</td>" +
                                    "<td style='width:12.5%;display:none;'>" + fld[0] + "</td>" +
                                    "<td style='width:12.5%;'>" + fld[1] + "</td>" +
                                    "<td style='width:12.5%;display:none;'>" + fld[2] + "</td>" +
                                    "<td style='width:12.5%;'>" + fld[3] + "</td>" +
                                    "<td style='width:12.5%;display:none;'>" + fld[4] + "</td>" +
                                    "<td style='width:12.5%;'>" + fld[5] + "</td>" +
                                    "<td style='width:12.5%;'>" + fld[6] + "</td>" +
                                    "<td style='width:7.5%;'>" + fld[7] + "</td>" +
                                    "<td style='width:7.5%;'>" + fld[8] + "</td>" +
                                    "<td style='width:8%;'><input type='text' class='form-control txtExtCustLocWarr' id='txtExtCustLocWarr"+m_asset_idx+"' value='"+fld[9]+"'></td>" +
                                    "<td style='width:8%;'><input type='text' class='form-control txtExtCustLocWarrEnd' id='txtExtCustLocWarrEnd"+m_asset_idx+"' value='"+fld[10]+"'></td>" +
                                    "<td style='width:3%;'><input type='number' class='form-control txtCycle' id='txtCycle"+m_asset_idx+"' value='"+fld[11]+"'></td>" +
                                    "<td style='width:3%;'></td>" +
                                    "<td style='text-align:center;'><a href='javascript:' onclick='removeCustomerAsset(" + m_asset_idx + ")'><span class='glyphicon glyphicon-trash'></span></a></a></td></tr>"); 
            
        }
    }
    $('.txtExtCustLocWarr').datepicker({
        format: "dd/mm/yyyy"
    });
    $('.txtExtCustLocWarr').on('changeDate', function(ev){
        $(this).datepicker('hide');
    });

    $('.txtExtCustLocWarrEnd').datepicker({
        format: "dd/mm/yyyy"
    });
    $('.txtExtCustLocWarrEnd').on('changeDate', function(ev){
        $(this).datepicker('hide');
    });
}

function updateCustomerLocation() {
    saveCustomerLocation(C_UPDATE) ; 
}

function saveCustomerLocation(type){
    if (validateCustomerLocation()){
        var data = {        "type"              : type,
                            "id"                : $('#txtCustLocID').val(),
                            "code"              : $('#txtCustLocCode').val(),
                            "name"              : $('#txtCustLocName').val(), 
                            "custid"            : $('#cobCustLocCustId').val(),
                            "contactname"       : $('#txtCustLocContactName').val(),
                            "contactphone"      : $('#txtCustLocContactPhone').val(),
                            "contactemail"      : $('#txtCustLocContactEmail').val(),
                            "address"           : $('#txtCustLocAddress').val(),
                            "postal_code"       : $('#txtCustLocContactPostal').val(),
                            "asset"             : getAsset()

                        };
        var url  = "index.pzx?c=" + customerloc_url + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onCustomerLocationResponse,customerloc_obj) ;
    } 
}

function getAsset(){
    var lines           = "" ;
    var sep             = "" ;
    $('#customer-asset-table tr').each(function() { 
        product         = $(this).find("td").eq(1).html()  ;
        brand           = $(this).find("td").eq(3).html()  ;
        model           = $(this).find("td").eq(5).html()  ;
        serialnumb      = $(this).find("td").eq(7).html()  ;
        warrstart       = $(this).find("td").eq(8).html()  ;
        warrend         = $(this).find("td").eq(9).html()  ;
        extwarrstart    = $('.txtExtCustLocWarr',this).val()  ;
        extwarrend      = $('.txtExtCustLocWarrEnd',this).val()  ;
        cycle           = $('.txtCycle',this).val()  ;
        schdate         = ''  ;
        
        lines           = lines + sep + product + "~" + brand + "~" + model + "~" + serialnumb + "~" + warrstart + "~" + warrend+ "~" + extwarrstart+ "~" + extwarrend+ "~" + cycle+ "~" + schdate;
        sep             = "|" ;
    }); 
    console.log(lines);
    return lines ;
    
}

function validateCustomerLocation(){
    
    if ($('#txtCustLocCode').blank()) {
        showMessage('error', "Location Code cannot be blank", "Warning");
        return false;
    }
    if ($('#txtCustLocName').blank()) {
        showMessage('error', "Location Name cannot be blank", "Warning");
        return false;
    }
    if ($('#txtCustLocContactPostal').blank()) {
        showMessage('error', "Postal Code cannot be blank", "Warning");
        return false;
    }
    if ($('#cobCustLocCustId').val()==0) {
        showMessage('error', "Customer cannot be blank", "Warning");
        return false;
    }
    return true;
}

function popupDeleteCustomerLocation(id, obj){
    var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                     "<button onclick=\"return deleteCustomerLocation(" + id + ", this);\" class=\"btn btn-danger\" > Delete </button>";
    $('#modalDeleteCustomerLocationConfirmationButton').html(strBtn);
    $('#modalDeleteCustomerLocationConfirmationContent').html("Are you sure you want to delete this Customer Location?");
    $('#modalDeleteCustomerLocationConfirmationTitle').html("Delete Customer Location");
    $("#deleteCustomerLocationConfirmationView").modal("show");
}

function deleteCustomerLocation(id, obj) {
    $("#deleteCustomerLocationConfirmationView").modal("hide");
    var data = { 
            "id"            : id,
            "type"          : C_DELETE_CUST_LOC
            };
    var url = "index.pzx?c=" + customerloc_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onCustomerLocationResponse,obj) ;
}

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

    if(resp.type == C_CUST_LOC_FILTER) {
        $('#customer-location-table').html('');
        $('#customer-location-table').append(resp.data);
    } else if (resp.type == C_ADD_CUST_LOC_VIEW || resp.type == C_UPDATE_CUST_LOC_VIEW) {
        $("#addCustomerLocationView").modal("show");
        $('#modalAddCustomerLocationHeaderViewContent').html(resp.data.all);
        var functionName = "addCustomerLocation()";
        if (resp.type == C_UPDATE_CUST_LOC_VIEW) {
            $('#txtCustLocID').val(resp.data.headerData.id) ;
            $('#txtCustLocCode').val(resp.data.headerData.code) ;
            $('#txtCustLocName').val(resp.data.headerData.name) ;
            $('#cobCustLocCustId').val(resp.data.headerData.custid) ;
            $('#txtCustLocContactName').val(resp.data.headerData.contactname) ;
            $('#txtCustLocContactPhone').val(resp.data.headerData.contactphone) ;
            $('#txtCustLocContactEmail').val(resp.data.headerData.contactemail) ;
            $('#txtCustLocAddress').val(resp.data.headerData.address) ;
            $('#txtCustLocContactPostal').val(resp.data.headerData.postal_code) ;
            
            showCustomerAsset(resp.data.headerData.customer_asset);

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

        $('#modalAddCustomerLocationHeaderViewButtonContent').show().html(strBtn); 
    } else if (resp.type == C_ADD) {
        showMessage('success', resp.mesg, "Success");

        $('#customer-location-table tbody:first tr:first').after(
                "<tr id='customer-location-rows-" + resp.data.id + "'>" + 
                "<td style='display:none'>" + resp.data.id + "</td>" + 
                "<td>" + resp.data.code + "</td>" +
                "<td>" + resp.data.name + "</td>" +
                "<td>" + resp.data.customer + "</td>" + 
                "<td><div><button  title=\"View\" onclick=\"return showEditCustomerLocation('" + resp.data.id + "', this);\" id='btnEdit' data-toggle='modal' class='btn btn-primary glyphicon glyphicon-edit btn-sm'></button>" +
                "<button  title=\"Delete\" onclick=\"return popupDeleteCustomerLocation('" + resp.data.id + "', this);\" id='btnDelete' data-toggle='modal' class='btn btn-danger glyphicon glyphicon-trash btn-sm'></button>" +
                "</div></td>" +
                "</tr>"); 

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

        $($(obj).closest('tr')).children('td:eq(1)').text(resp.data.code) ;
        $($(obj).closest('tr')).children('td:eq(2)').text(resp.data.name) ;
        $($(obj).closest('tr')).children('td:eq(3)').text(resp.data.customer) ;
    } else if (resp.type == C_DELETE_CUST_LOC) {
        showMessage('success', resp.mesg, "Success");
        $('#customer-location-rows-'+resp.data).remove() ;
    } else if (resp.type == C_GET + '_MODEL') {
        $("#cobCustLocModel").html(resp.data.model);
    }
}
