var C_GOODS_RECEIVING_FILTER       = "1701";
var C_ADD_GOODS_RECEIVING_VIEW     = "1702";
var C_UPDATE_GOODS_RECEIVING_VIEW  = "1703";
var C_DELETE_GOODS_RECEIVING       = "1704";

var goodsreceiving_obj             = null;
var index   = 0;
var m_comm_idx = 0;

function changeProspect() {
    if($('#toggle-one').is(':checked')){
        $('#divProsLabel').hide();
        $('#divPros').hide();

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

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

function filterGoodsReceiving(){
    var date = $('#dateFilterGRN').val();
    var cust = $('#compFilterGRN').val();
    var grnId = $('#txtFilterGRCode').val();


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

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

function showAddGoodsReceivingInquiry(){
    showProgress("loading Project" ) ;
    
    var data = { "type": "C_ADD_GOODS_RECEIVING_INQUIRY_VIEW"} ;
    var url  = "index.pzx?c=" + goodsreceiving_url + "&t=" + "C_ADD_GOODS_RECEIVING_INQUIRY_VIEW"  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsReceivingResponse,null) ;
}

function showAddGoodsReceiving(){
    showProgress("loading Project" ) ;
    
    var data = { "type": C_ADD_GOODS_RECEIVING_VIEW} ;
    var url  = "index.pzx?c=" + goodsreceiving_url + "&t=" + C_ADD_GOODS_RECEIVING_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsReceivingResponse,null) ;
}

function addGoodsReceivingDetail(obj) {

    index++;

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

    $('#goodsreceivingItemTableBody').append("<tr id='trGoodsReceivingDetail" + index + "'>"+
                                        "<td >" + index + "</td>" +
                                        // "<td >" + "<input  class='form-control cmbItemCode' id='itemCode"+index+"' >" + "</td>" +
                                        "<td >" + cmbItem + "</td>" +
                                        "<td >" + "<input  class='form-control txtItemDesc' id='itemDesc"+index+"' ><span id='txtCommand"+index+"' style='color:blue;margin-left:25px;'></span>" + "</td>" +
                                        "<td >" + "<input  class='form-control txtItemBrand' id='itemBrand"+index+"' >" + "</td>" +
                                        "<td >" + "<input  class='form-control txtItemSerialNumb' id='itemSerialNumb"+index+"' >" + "</td>" +
                                        "<td style='display:none;'>" + "<label id='lblCommand"+index+"' ></label>" + "</td>" +
                                        '<td style="text-align:center;"><button class="btn btn-primary" onclick="showLineCommand('+index+');">LC</button></td>'+
                                        "<td >" + "<input type='number' min='1' style='text-align:right;' class='form-control txtItemQty' id='itemQty"+index +"' >"  + "</td>" +
                                        '<td style="width:40px;text-align:center;"><button title="Delete" onclick="javascript: deleteGoodsReceivingDetail('+index+', this);" id="btnDelete" data-toggle="modal" class="btn btn-danger glyphicon glyphicon-trash btn-sm"></button></td></tr>'); 

    var option ={
                theme: "bootstrap",
                placeholder: "Select Customer",
                width: "auto",
                dropdownAutoWidth: true,
                allowClear: true,
            };
    $('#goodsreceivingItemTableBody tr').each(function() { 
        $(".cmbItemCode").select2(option);
    }); 

    $('#lblItemBrand'+index).val($('#itemBrand'+index).val());

    // clearGoodsReceivingDetail(index);
}
function populateDescription(index) {

    $('#cmbItemDescOpt').val($('#itemCode'+index).val()).trigger('change');
    $('#itemDesc'+index).val("");
    $('#itemDesc'+index).val($('#cmbItemDescOpt :selected').text());

    $('#cmbItemBrandOpt').val($('#itemCode'+index).val()).trigger('change');
    $('#itemBrand'+index).val("");
    $('#itemBrand'+index).val($('#cmbItemBrandOpt :selected').text());
}
function deleteGoodsReceivingDetail(idx) {
    $('#trGoodsReceivingDetail'+idx).remove() ;
}

function clearGoodsReceivingDetail(index) {
    $('.btnAddDetail').closest('tr').find('td .txtItemDesc').val('');
    $('.btnAddDetail').closest('tr').find('td .txtItemBrand').val('');
    $('.btnAddDetail').closest('tr').find('td .txtItemSerialNumb').val('');
    $('.btnAddDetail').closest('tr').find('td .txtItemQty').val(0);
}

function showCommunicationForm(){
    clearCommunication();
    $('#communicationPanel').show('slow') ;
}

function closeCommunicationForm(){
    clearCommunication();
    $('#communicationPanel').hide('slow') ;
}

function addCommunication() {
    if($('#txtComCustName').blank() || $('#txtComCustContact').blank()){
        showMessage('error', "Please fill all the field first!", "Warning");
        return false;
    }

    //var date = moment(new Date($('#txtComDate').val())).format('DD Month YYYY');

    m_comm_idx++;
    $('#communication-table-body').append("<tr id='trCommunication" + m_comm_idx + "'><td style='width:30px;display:none'>" +m_comm_idx+ "</td>" +
        "<td>" + $('#txtComDate').val() + "</td>" +
        "<td>" + $('#txtComCustName').val() + "</td>" +
        "<td>" + $('#txtComCustContact').val() + "</td>" +
        "<td>" + $('#cmbComMethod :selected').text() + "</td>" +
        "<td style='display:none;'>" + $('#cmbComMethod :selected').val() + "</td>" +
        "<td></td>" +
        "<td></td>"); 

    clearCommunication();
}

function clearCommunication() {
    $('#txtComCustName').val('') ;
    $('#txtComCustContact').val('') ;
}

function changeMethod() {
    if($('#cmbComMethod').val() == 1){
        $('#lblComEmail').attr("style", "display:none");
        $('#lblComPhone').attr("style", "display:show");
    }else if ($('#cmbComMethod').val() == 2){
        $('#lblComEmail').attr("style", "display:show");
        $('#lblComPhone').attr("style", "display:none");
    }
}

function addGoodsReceiving() {
    saveGoodsReceiving(C_ADD);
}

function showEditGoodsReceiving(id, obj) {
    goodsreceiving_obj = obj ;
    showProgress("loading Goods Receiving" ) ;
    var data  = { "type": C_UPDATE_GOODS_RECEIVING_VIEW, "id" : id} ;
    var url   = "index.pzx?c=" + goodsreceiving_url + "&t=" + C_UPDATE_GOODS_RECEIVING_VIEW  + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsReceivingResponse,null) ;
}

function showGoodsReceivingDetail(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" style="width:100%">'+$('#cmbItemCodeOpt').html()+'</select>';

            $('#goodsreceivingItemTableBody').append("<tr id='trGoodsReceivingDetail" + 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] +"'><span id='txtCommand"+index+"' style='color:blue;margin-left:25px;'>"+fld[5] +"</span>" + "</td>" +
                                    "<td >" + "<input  class='form-control txtItemBrand' id='itemBrand"+index+"' value='"+fld[6] +"'>" + "</td>" +
                                    "<td >" + "<input  class='form-control txtItemSerialNumb' id='itemSerialNumb"+index+"' value='"+fld[3] +"'>" + "</td>" +
                                    "<td style='display:none;'>" + "<label id='lblCommand"+index+"'>"+fld[5] +"</label>" + "</td>" +
                                    '<td style="text-align:center;"><button class="btn btn-primary" onclick="showLineCommand('+index+');">LC</button><br></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: deleteGoodsReceivingDetail('+index+', this);" id="btnDelete" data-toggle="modal" class="btn btn-danger glyphicon glyphicon-trash btn-sm"></button></td></tr>'); 
            
            $('#itemCode'+index).val(fld[1]);
          var option = {
            theme: "bootstrap",
            placeholder: "Item Code",
            width: "140px",
            dropdownAutoWidth: true,
            allowClear: true,
            };
            $(".cmbItemCode").select2(option);
            
            $('#lblItemBrand'+index).val(fld[6]);

        }
    }
}

function showLineCommand(idx) {
    $("#showGoodsReceivingLCView").modal("show");

    $("#modalShowGoodsReceivingLCViewContent").html(''+
                    // '<label style="text-align:left;margin-top:5px;" for="lblItemBrand" class="col-md-2 control-label">Brand</label>'+
                    // '<div class="col-sm-4">'+
                    //      '<input id="lblItemBrand'+idx+'" maxlength="100" type="text" class="form-control">'+
                    // '</div>'+
                    // '<label style="text-align:left;" for="txtItemBrand" class="col-md-2 control-label">Model</label>'+
                    // '<div class="col-sm-4">'+
                         // '<input id="txtItemModel'+idx+'" maxlength="100" type="text" class="form-control" readonly>'+
                    // '</div>'+
                    '<br><br><br>'+
                    '<textarea class="form-control" rows="3" maxlength="250" id="txtLCCommand'+idx+'"></textarea> ');

    if($("#txtCommand"+idx).text()!="") {
        $("#txtLCCommand"+idx).val($("#txtCommand"+idx).text()); 
    }
    $('#lblItemBrand'+idx).val($('#itemBrand'+idx).val());

    var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                        "<button id=\"btnSaveLC\" class=\"btn btn-primary\" onclick=\"saveLineCommand("+idx+");\">Save</button>" ;

    $('#modalShowGoodsReceivingLCButtonContent').show().html(strBtn); 
    
}

function saveLineCommand(idx) {
    $("#showGoodsReceivingLCView").modal("hide");
    command = $("#txtLCCommand"+idx).val();
    $("#txtCommand"+idx).text(command);
    $("#lblCommand"+idx).text(command);
}

function showGoodsReceivingCommunication(lines) {
    if (lines == undefined || lines == null || lines == "") return ;
    
    var line = lines.split('|') ;
    var fld = "" ;
    m_comm_idx = 0 ;
    for (var i = 0 ; i < line.length ; i++) {
        if (line[i] != "") {
            fld = line[i].split('~') ;
            m_comm_idx++;
            $('#communication-table-body').append("<tr id='trCommunication" + m_comm_idx + "'><td style='width:30px;display:none'>" +fld[0]+ "</td>" +
                                    "<td >" + fld[1] + "</td>" +
                                    "<td >" + fld[2] + "</td>" +
                                    "<td >" + fld[3] + "</td>" +
                                    "<td >" + fld[4] + "</td>" +
                                    "<td style='display:none'>" + fld[5] + "</td>");   
        }
    }
}

function updateGoodsReceiving() {
    saveGoodsReceiving(C_UPDATE) ; 
}

function saveGoodsReceiving(type){
    var data = {        "type"              : type,
                        "id"                : $('#txtGRID').val(),
                        "date"              : $('#txtGRDate').val(),
                        "time"              : $('#txtGRTime').val(),
                        "user_loc"          : $('#cobGRLoc').val(),
                        "user_id"           : $('#txtLoginId').val(),
                        "user_coy"          : $('#txtLoginCoyId').val(),
                        "status_cust"       : ($('#toggle-one').is(':checked') ? '1' : '0'),
                        "cust_coy"          : $('#cmbCustCoyName').val(),
                        "prospect_name"     : $('#txtProsName').val(),
                        "contact_name"      : $('#txtContactName').val(),
                        "contact_phone"     : $('#txtContactPhone').val(),
                        "contact_email"     : $('#txtContactEmail').val(),
                        "detail"            : getDetail(),
                        "communication"     : getCommunication()

                    };

    var url  = "index.pzx?c=" + goodsreceiving_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsReceivingResponse,goodsreceiving_obj) ;
}

function getDetail(){
    var lines           = "" ;
    var sep             = "" ;
    $('#goodsreceivingItemTableBody tr').each(function() { 
        itemCode        = $('.cmbItemCode',this).val()  ;
        itemDesc        = $('.txtItemDesc',this).val()  ;
        serialnumb      = $('.txtItemSerialNumb',this).val()  ;
        itemQty         = $('.txtItemQty',this).val()  ;
        comment         = $(this).find("td").eq(5).text()  ;
        itemBrand       = $('.txtItemBrand',this).val()  ;

        lines           = lines + sep + itemCode + "~" + itemDesc + "~" + serialnumb + "~" + itemQty + "~" + comment + "~" + itemBrand;
        sep             = "|" ;
        
    }); 
console.log(lines);
    return lines ;
}

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 popupDeleteGoodsReceiving(id, obj){
    var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                     "<button onclick=\"return deleteGoodsReceiving(" + id + ", this);\" class=\"btn btn-danger\" > Delete </button>";
    $('#modalDeleteGoodsReceivingConfirmationButton').html(strBtn);
    $('#modalDeleteGoodsReceivingConfirmationContent').html("Are you sure you want to delete this Goods Receiving?");
    $('#modalDeleteGoodsReceivingConfirmationTitle').html("Delete Goods Receiving");
    $("#deleteGoodsReceivingConfirmationView").modal("show");
}

function deleteGoodsReceiving(id, obj) {
    $("#deleteGoodsReceivingConfirmationView").modal("hide");
    var data = { 
            "id"            : id,
            "type"          : C_DELETE_GOODS_RECEIVING
            };
    var url = "index.pzx?c=" + goodsreceiving_url + "&d=" + new Date().getTime() ;
    callServer(url,"json",data,onGoodsReceivingResponse,obj) ;
}

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

    if(resp.type == C_GOODS_RECEIVING_FILTER) {
        $('#goods-receiving-table').html('');
        $('#goods-receiving-table').append(resp.data);
    } else if (resp.type == C_ADD_GOODS_RECEIVING_VIEW || resp.type == C_UPDATE_GOODS_RECEIVING_VIEW) {
        $("#addGoodsReceivingView").modal("show");
        $('#modalAddGoodsReceivingContent').html(resp.data.all);

        var functionName = "addGoodsReceiving()";
        var name = "Add";
        var disabled = "disabled";
        var grn_id  = 0 ;

        $('#cobGRLoc').val(resp.data.headerData.userLoc) ;
        $('#cobGRLoc').select2({
            data: function() { return {results: resp.data.headerData.userLoc}; }
        });

       if (resp.type == C_UPDATE_GOODS_RECEIVING_VIEW) {
            
            $('#txtLoginId').val(resp.data.headerData.loginId) ;
            $('#txtLoginCoyId').val(resp.data.headerData.loginCoyId) ;
            $('#txtLoginName').val(resp.data.headerData.loginName) ;
            $('#txtLoginEmail').val(resp.data.headerData.loginEmail) ;
            $('#txtLoginPhone').val(resp.data.headerData.loginPhone) ;

            if(resp.data.headerData.status_cust == '1'){
                $('#toggle-one').bootstrapToggle('on');
                changeProspect();
            } else {
                $('#toggle-one').bootstrapToggle('off');
                changeProspect();
            }
            $('#cmbCustCoyName').val(resp.data.headerData.cust) ;
            $('#cmbCustCoyName').select2({
                    data: function() { return {results: resp.data.headerData.cust}; }
                });
            $('#txtProsName').val(resp.data.headerData.prospect) ;
            $('#txtContactName').val(resp.data.headerData.prospectname) ;
            $('#txtContactPhone').val(resp.data.headerData.prospectphone) ;
            $('#txtContactEmail').val(resp.data.headerData.prospectemail) ;
            $('#txtGRID').val(resp.data.headerData.id) ;
            $('#txtGRDate').val(resp.data.headerData.date) ;
            $('#txtGRTime').val(resp.data.headerData.time) ;
            grn_id = resp.data.headerData.id;
            showGoodsReceivingDetail(resp.data.headerData.detail);
            showGoodsReceivingCommunication(resp.data.headerData.communication);

            functionName = "updateGoodsReceiving()";
            var disabled = "";
            name = "Update";
        }
        var strBtn = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Cancel</button>" +
                        "<button id=\"btnGoodsReceivingAdd\" class=\"btn btn-primary\" onclick=\"return "+functionName+";\">"+name+"</button>"+
                        "<button id=\"btnGoodsReceivingEmail\" onclick='sendEmailNow("+grn_id+",this)' class=\"btn btn-info\" "+disabled+">Email</button>"+
                        "<button type=\"button\" class=\"btn btn-success\" onclick=\"return printGrn("+grn_id+");\" "+disabled+">Print</button>" ;

        $('#modalAddGoodsReceivingFooter').show().html(strBtn); 
        
        var option = {
            theme: "bootstrap",
            placeholder: "Select Customer",
            width: "auto",
            dropdownAutoWidth: true,
            allowClear: true,
        };

        $("#cobGRLoc").select2(option);
        $("#cmbCustCoyName").select2(option);
        $("#cmbItemCodeOpt").select2(option);
      
    } else if (resp.type == C_ADD) {
        showMessage('success', resp.mesg, "Success");

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

        $("#addGoodsReceivingView").modal("hide");
        filterGoodsReceiving();
    } else if (resp.type == C_DELETE_GOODS_RECEIVING) {
        showMessage('success', resp.mesg, "Success");
        $('#goods-receiving-rows-'+resp.data).remove() ;
    } else if (resp.type == "C_ADD_GOODS_RECEIVING_INQUIRY_VIEW" ) {
        $("#showGoodsReceivingInquiryView").modal("show");
        $("#modalShowGoodsReceivingInquiryViewTitle").html(resp.data.headTitle);
        $("#modalShowGoodsReceivingInquiryViewContent").html(resp.data.htmlContent);
             
    }
}
var enableSubmit = function(id,ele) {
    $(ele).removeAttr("disabled");
    
}

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

};
function dosomething(id) {
    // console.log("asdas");
    var data = { "type": "GRN_SEND_EMAIL", "grn_id":id} ;
	var url = "index.pzx?c=" + goodsreceiving_url + "&d=" + new Date().getTime() ;		
	callServer(url,"json",data,onEmailResponse,goodsreceiving_obj) ;
}
function onEmailResponse(obj,resp) {
	if (resp.status == C_OK) {
		if(resp.type == "GRN_SEND_EMAIL"){
			showMessage('success', resp.mesg, "Success");
            $("#addGoodsReceivingView").modal("hide");
		}		
	} else {
        showMessage('error', resp.mesg, "Warning");
        return false;
    }
}

function printGrn (id){
    var url = "index.pzx?c=" + goodsreceiving_url + "&id=" + id + "&t=" + "SHOW_REPORT" + "&r=1";
    showReport(url) ;
}
// function showProspectDetail() {
//     $('#showProspectDetail').modal('show');
// }

// function getGoodsReceivingAutoSearch(){
//     var data = { "type": "C_SEARCH" } ;
//     var url = "request.pzx?c=" + goodsreceiving_url + "&d=" + new Date().getTime() ;
//     callServer(url,"json",data,onGoodsReceivingAutoSearch,goodsreceiving_obj) ;
// }

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

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

// function showInquiryDetail() {
//     showAddGoodsReceiving();
// }

