var C_GOODS_DELIVER_FILTER       = "1801";
var C_ADD_GOODS_DELIVER_VIEW     = "1802";
var C_UPDATE_GOODS_DELIVER_VIEW  = "1803";

var goodsdeliver_obj             = null;
var index   = 0;
var m_comm_idx = 0;


function filterGoodsDeliver(){
    var date = $('#dateFilterGDN').val();
    var cust = $('#compFilterGDN').val();
    var grnId = $('#txtFilterGRCode').val();


    var data = { "type"     : C_GOODS_DELIVER_FILTER,
                 "date"     : date, 
                 "cust"     : cust,
                 "grnId"    : grnId
                };

    var url  = "index.pzx?c=" + goodsdeliver_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsDeliverResponse,null) ;
}
function showAddGoodsDeliver(){
    showProgress("loading Project" ) ;
    
    var data = { "type": C_ADD_GOODS_DELIVER_VIEW} ;
    var url  = "index.pzx?c=" + goodsdeliver_url + "&t=" + C_ADD_GOODS_DELIVER_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsDeliverResponse,null) ;
}
function addGoodsDeliver() {
    saveGoodsDeliver(C_ADD);
}

function updateGoodsDeliver() {
    saveGoodsDeliver(C_UPDATE) ; 
}

function saveGoodsDeliver(type){
    var data = {        "type"              : type,
                        "id"                : $('#txtGDID').val(),
                        "grn_id"            : $('#cmbGRNID').val(),
                        "loc_id"            : $('#cobGDLoc').val(),
                      
                    };

    var url  = "index.pzx?c=" + goodsdeliver_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsDeliverResponse,goodsdeliver_obj) ;
}
function showEditGoodsDelivery(id, obj) {
    goodsdeliver_obj = obj ;
    showProgress("loading Goods Deliver" ) ;
    var data  = { "type": C_UPDATE_GOODS_DELIVER_VIEW, "id" : id} ;
    var url   = "index.pzx?c=" + goodsdeliver_url + "&t=" + C_UPDATE_GOODS_DELIVER_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsDeliverResponse,null) ;
}

function showGoodsDeliverDetail(lines) {
    if (lines == undefined || lines == null || lines == "") return ;
    
    var line = lines.split('|') ;
    var fld = "" ;
    index = 0 ;
    for (var i = 0 ; i < line.length ; i++) {
        if (line[i] != "") {
            fld = line[i].split('~') ;
            index++;

            var cmbItem = '<select id="itemCode'+index+'" onchange="populateDescription('+index+',this)" class="form-control cmbItemCode">'+$('#cmbItemCodeOpt').html()+'</select>';

            $('#goodsdeliverItemTableBody').append("<tr id='trGoodsDeliverDetail" + index + "'>"+
                                    "<td >" + index + "</td>" +
                                    // "<td >" + "<input  class='form-control cmbItemCode' id='itemCode"+index+"' value='"+fld[1] +"'>" + "</td>" +
                                    "<td >" + cmbItem + "</td>" +
                                    "<td >" + "<input  class='form-control txtItemDesc' id='itemDesc"+index+"' value='"+fld[2] +"'>" + "</td>" +
                                    "<td >" + "<input  class='form-control txtItemSerialNumb' id='itemSerialNumb"+index+"' value='"+fld[3] +"'>" + "</td>" +
                                    '<td style="text-align:center;"><button class="btn btn-primary">LC</button></td>'+
                                    "<td >" + "<input type='number' min='1' style='text-align:right;' class='form-control txtItemQty' id='itemQty"+index +"' value='"+fld[4] +"'>"  + "</td>" +
                                    '<td style="width:40px;text-align:center;"><button title="Delete" onclick="javascript: deleteGoodsDeliverDetail('+index+', this);" id="btnDelete" data-toggle="modal" class="btn btn-danger glyphicon glyphicon-trash btn-sm"></button></td></tr>'); 
            
            $('#itemCode'+index).val(fld[1]);
        }
    }
}


function getCommunication(){
    var lines           = "" ;
    var sep             = "" ;
    $('#communication-table-body tr').each(function() { 
        date            = $(this).find("td").eq(1).html()  ;
        custname        = $(this).find("td").eq(2).html()  ;
        contact         = $(this).find("td").eq(3).html()  ;
        method          = $(this).find("td").eq(5).html()  ;
        
        lines           = lines + sep + date + "~" + custname + "~" + contact + "~" + method;
        sep             = "|" ;
    }); 

    return lines ;
}


function popupDeleteGoodsDeliver(id, obj){
    var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                     "<button onclick=\"return deleteGoodsDeliver(" + id + ", this);\" class=\"btn btn-danger\" > Delete </button>";
    $('#modalDeleteGoodsDeliverConfirmationButton').html(strBtn);
    $('#modalDeleteGoodsDeliverConfirmationContent').html("Are you sure you want to delete this Goods Deliver?");
    $('#modalDeleteGoodsDeliverConfirmationTitle').html("Delete Goods Deliver");
    $("#deleteGoodsDeliverConfirmationView").modal("show");
}

function deleteGoodsDeliver(id, obj) {
    $("#deleteGoodsDeliverConfirmationView").modal("hide");
    var data = { 
            "id"            : id,
            "type"          : C_DELETE
            };
    var url = "index.pzx?c=" + goodsdeliver_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsDeliverResponse,obj) ;
}
function populateGrn(grn_id){
    showProgress("loading Project" ) ;
    
    var data = { "type": "POPULATE_GRN" , loc_id:$('#cobGDLoc').val(), grn_id: grn_id} ;
    var url  = "index.pzx?c=" + goodsdeliver_url + "&t=" + "POPULATE_GRN"  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsDeliverResponse,null) ;
}

function populateGrnDetail(id){
    showProgress("loading Project" ) ;
    
    var data = { "type": "POPULATE_GRN_DETAIL" , grn_id:$('#cmbGRNID :selected').val()} ;
    var url  = "index.pzx?c=" + goodsdeliver_url + "&t=" + "POPULATE_GRN_DETAIL"  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsDeliverResponse,null) ;
}
function onGoodsDeliverResponse(obj,resp){
	$('#activityLoadingModal').modal('hide');
    if (resp.status != C_OK ) {
        showMessage('error', resp.mesg, "Warning");
        return false;
    }

    if(resp.type == C_GOODS_DELIVER_FILTER) {
        $('#goods-deliver-table').html('');
        $('#goods-deliver-table').append(resp.data);
    } else if (resp.type == C_ADD_GOODS_DELIVER_VIEW || resp.type == C_UPDATE_GOODS_DELIVER_VIEW) {
        $("#addGoodsDeliverView").modal("show");
        $('#modalAddGoodsDeliverContent').html(resp.data.all);

        var functionName = "addGoodsDeliver()";
        var name = "Add";
        var disabled = "disabled";
        var gdn_id = 0;
        var grn_id = 0;
        $('#cobGDLoc').val(resp.data.userLoc);

        
       if (resp.type == C_UPDATE_GOODS_DELIVER_VIEW) {
            
            $('#cmbGRNID').val(resp.data.grn_id) ;
            grn_id = resp.data.grn_id
            
            $('#txtGDID').val(resp.data.id) ;
           
            gdn_id = resp.data.id;
        
            functionName = "updateGoodsDeliver()";
            var disabled = "";
            name = "Update";
        }
        populateGrn(grn_id);
        var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                        "<button id=\"btnGoodsDeliverAdd\" class=\"btn btn-primary\" onclick=\"return "+functionName+";\">"+name+"</button>"+
                        "<button id=\"btnGoodsDeliverEmail\" onclick='sendEmailNowGdn("+gdn_id+",this)' class=\"btn btn-info\" "+disabled+">Email</button>"+
                        "<button type=\"button\" class=\"btn btn-success\" onclick=\"return printGdn("+gdn_id+");\" "+disabled+">Print</button>" ;

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

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

        $("#addGoodsDeliverView").modal("hide");
        filterGoodsDeliver();
    } else if (resp.type == C_DELETE) {
        showMessage('success', resp.mesg, "Success");
        $('#goods-deliver-rows-'+resp.data).remove() ;
    } else if (resp.type == "C_ADD_GOODS_DELIVER_INQUIRY_VIEW" ) {
        $("#showGoodsDeliverInquiryView").modal("show");
        $("#modalShowGoodsDeliverInquiryViewTitle").html(resp.data.headTitle);
        $("#modalShowGoodsDeliverInquiryViewContent").html(resp.data.htmlContent);
             
    }else if (resp.type == "POPULATE_GRN") {
        
        $("#cmbGRNID").html(resp.data.all);
        $("#cmbGRNID").val(resp.data.grn_id).trigger("change");
             
    }else if(resp.type == "POPULATE_GRN_DETAIL"){
        
        $('#cmbCustCoyName').val(resp.data.customer) ;
        $('#txtCustCoyName').html($('#cmbCustCoyName :selected').text() );

        $('#txtProsName').html(resp.data.prospect) ;
        $('#txtContactName').html(resp.data.contact) ;
        $('#txtContactPhone').html(resp.data.phone) ;
        $('#txtContactEmail').html(resp.data.email) ;
        $('#txtGRID').html(resp.data.code) ;
        $('#txtGRDate').val(resp.data.date) ;
        $('#txtGRTime').val(resp.data.time) ;
       
        if(resp.data.status_cust == '1'){
            
         
            changeGdnProspect(true);
        } else {
            
            changeGdnProspect(false);
        }
        showGRNDetail(resp.data.detail);

        
    }
}

function changeGdnProspect(toogle) {
    if(toogle){
        $('#divProsLabel').hide();
        $('#divPros').hide();

        $('#divComLabel').show();
        $('#divCom').show();
    }else{
        $('#divProsLabel').show();
        $('#divPros').show();

        $('#divComLabel').hide();
        $('#divCom').hide();
    }
}

function showGRNDetail(lines) {
    if (lines == undefined || lines == null || lines == "") return ;
    
    var line = lines.split('|') ;
    var fld = "" ;
    index = 0 ;
    for (var i = 0 ; i < line.length ; i++) {
        if (line[i] != "") {
            fld = line[i].split('~') ;
            index++;

            $('#goodsdeliverItemTableBody').append("<tr id='trGoodsReceivingDetail" + index + "'>"+
                                    "<td >" + index + "</td>" +
                                
                                    "<td >" + fld[1] + "</td>" +
                                    "<td ><span>" + fld[2] + "</span><br><span style='color:blue;margin-left:25px;'>"+fld[6]+"</span></td>" +
                                    "<td >" + fld[5] + "</td>" +
                                    "<td >" + fld[3] + "</td>"+
                                    "<td >" + fld[4] + "</td></tr>"); 
            
        }
    }
}
// var enableSubmit = function(id,ele) {
//     $(ele).removeAttr("disabled");
    
// }

// function sendEmailNow(id,obj) {
    
//     var that = obj;
//     $(obj).attr("disabled", true);
//     setTimeout(function() { enableSubmit(id,that) }, 5000);
//     dosomething(id) ;

// };
// function dosomething(id) {
//     var data = { "type": "GDN_SEND_EMAIL", "grn_id":id} ;
// 	var url = "index.pzx?c=" + goodsdeliver_url + "&d=" + new Date().getTime() ;		
// 	callServer(url,"json",data,onEmailResponse,goodsdeliver_obj) ;
// }
// function onEmailResponse(obj,resp) {
// 	if (resp.status == C_OK) {
// 		 if(resp.type == "GDN_SEND_EMAIL"){
			
// 		}		
// 	} else {
//         showMessage('error', resp.mesg, "Warning");
//         return false;
//     }
// }

function printGdn (id){
    var url = "index.pzx?c=" + goodsdeliver_url + "&id=" + id + "&t=" + "SHOW_REPORT" + "&r=1";
    showReport(url) ;
}


