// JavaScript Document
//invoice item: goods_id,unit_id,unit_name,goods_name,export_price,quantity,serial
//phieuxuatlequay,phieuxuatle,phieuxuatbuon,phieuxuatchuyenkho,phieuxuatkhac,
//phieunhapmua,phieunhaptralai,phieunhapchuyenkho,phieunhapkhac
g_pageobj['{_UID_}'] =
{
    m_uid: "{_UID_}",
    m_invoice_prd_index: "'{_INVOICE_TYPE_}{_UID_}'",
    m_invoice_type: "{_INVOICE_TYPE_}",
    m_contact_type: "{_CONTACT_TYPE_}",
    m_invoice_id: "{_INVOICEID_}",
    m_invoice_editmode: false,
    m_invoice_prd: [],
    m_contact_id: 0,
    m_saleman_id: 0,
    m_deploymentmans: null,
    setContactId(id) {
        this.m_contact_id = id;
        g_data[this.m_invoice_prd_index + "contactid"] = id;
    },
    setSalemanId(id) {
        this.m_saleman_id = id;
        g_data[this.m_invoice_prd_index + "salemanid"] = id;
    },
    deploymentManAdd(id, name, phone) {

        if (this.can_edit != true) return false;

        if (isEmpty(this.m_deploymentmans)) {
            if (isEmpty(g_data[this.m_invoice_prd_index + "deploymentmans"]))
                g_data[this.m_invoice_prd_index + "deploymentmans"] = new Array();
            this.m_deploymentmans = g_data[this.m_invoice_prd_index + "deploymentmans"];
        }

        //check exists
        for (i = 0; i < this.m_deploymentmans.length; i++) {
            if (this.m_deploymentmans[i][0] == id) {
                return false;
            }
        }

        this.m_deploymentmans[this.m_deploymentmans.length] = [id, name, phone];
        return true;
    },
    deploymentManRemove(id) {
        if (this.can_edit != true) return false;

        if (isEmpty(this.m_deploymentmans)) return false;
        for (i = 0; i < this.m_deploymentmans.length; i++) {
            if (this.m_deploymentmans[i][0] == id) {
                this.m_deploymentmans.splice(i, 1);
                return true;
            }
        }
        return false;
    },
    //switch giua cac tab se mat du lieu trong javascript, chua global de khoi phuc lai
    initGlobalDataMap: function () {
        this.m_contact_type = parseNumberVn(this.m_contact_type);
        this.m_invoice_id = parseNumberVn(this.m_invoice_id);

        if (!isEmpty(g_data[this.m_invoice_prd_index + "salemanid"]))
            this.m_saleman_id = g_data[this.m_invoice_prd_index + "salemanid"];
        if (!isEmpty(g_data[this.m_invoice_prd_index + "contactid"]))
            this.m_contact_id = g_data[this.m_invoice_prd_index + "contactid"];
        if (!isEmpty(g_data[this.m_invoice_prd_index + "deploymentmans"])) {
            this.m_deploymentmans = g_data[this.m_invoice_prd_index + "deploymentmans"];
        }
        if (!isEmpty(g_data[this.m_invoice_prd_index + "canedit"]))
            this.can_edit = g_data[this.m_invoice_prd_index + "canedit"];
        if (isEmpty(g_data[this.m_invoice_prd_index])) {
            g_data[this.m_invoice_prd_index] = new Array();
            this.m_invoice_prd = g_data[this.m_invoice_prd_index];
            if (this.m_invoice_id > 0) {
                this.m_invoice_editmode = true;
                this.invoiceLoad(this.m_invoice_id);
            }

        } else {
            this.m_invoice_prd = g_data[this.m_invoice_prd_index];
        }
        //invoice new sau khi save -> chuyen tab -> quay lai
        if (!isEmpty(g_data[this.m_invoice_prd_index + "invoiceid"])) {
            if (this.m_invoice_id == 0) this.m_invoice_id = g_data[this.m_invoice_prd_index + "invoiceid"];
        }
        /*
        var key="edit"+this.m_invoice_type+this.m_invoice_id;
        if(!isEmpty(g_data[key]))
        {
            var id=document.getElementById("pageheader"+this.m_uid);
            if(id.innerHTML.indexOf(" [SỬA]")<0)
                id.innerHTML=id.innerHTML+" [SỬA]";
            if(isEmpty(g_data[this.m_invoice_prd_index]))
            {
                g_data[this.m_invoice_prd_index]=new Array();
                this.invoiceLoad(g_data[key]);
            }else
            {
                if(g_data[this.m_invoice_prd_index].length==0)
                    this.invoiceLoad(g_data[key]);
            }
            //this.m_invoice_id=g_data[key];
            this.m_invoice_prd=g_data[this.m_invoice_prd_index];
        	
        }
        else
        {
            if(isEmpty(g_data[this.m_invoice_prd_index]))
            {
                g_data[this.m_invoice_prd_index]=new Array();
            }
        	
            //this.m_invoice_id=0;
            this.m_invoice_prd=g_data[this.m_invoice_prd_index];
        }	
        */
        return true;
    },
    invoiceLoad: function (invoice_id) {
        var url = '?page=' + this.m_invoice_type + '&pagesub=invoice_load&invoice_type=' + this.m_invoice_type + '&invoice_id=' + invoice_id;
        jQuery.ajax({
            url: url,
            data: "",
            type: "GET",
            success: function (data) {
                var iditem = null;
                if (isDataOk(data)) {
                    g_data[g_pageobj['{_UID_}'].m_invoice_prd_index + "canedit"] = true;
                    g_pageobj['{_UID_}'].can_edit = true;

                    data = getDataOk(data);
                    var argoods = data.split(g_split_row);

                    if (argoods.length < 2) {
                        showMsg(itxt("thatbai"), "NẠP PHIẾU");
                        return;
                    }
                    var goods;
                    goods = argoods[0].split(g_split_val);


                    //id,invoice_no,invoice_date,vat,invoice_money_discount,
                    //total_cost,comment,money_debit,invoice_discount,store_id,
                    //store_name,bank_account_id,bank_account_number,trade_user_id,trade_user_name
                    //trade_user_phone
                    if (goods.length == ds_invoice.length) {
                        var invoice_date = document.getElementById("invoice_date");
                        var invoice_vat = document.getElementById("invoice_vat");
                        var invoice_money_discount = document.getElementById("invoice_money_discount");

                        var invoice_debit = document.getElementById("invoice_debit");
                        var invoice_pay = document.getElementById("invoice_pay");
                        var invoice_bankaccount = document.getElementById("invoice_bankaccount");
                        var invoice_comment = document.getElementById("invoice_comment");
                        var invoice_discount = document.getElementById("invoice_discount");


                        invoice_date.value = goods[2];
                        invoice_vat.value = formatNumber(goods[3]);
                        invoice_money_discount.value = formatNumber(goods[4]);
                        invoice_debit.value = formatNumber(goods[7]);
                        invoice_discount.value = formatNumber(goods[8]);
                        invoice_comment.innerHTML = goods[6];
                        selectItemByValue("select_store_id", goods[9]);
                        selectItemByValue("invoice_bankaccount", goods[11]);
                        g_pageobj['{_UID_}'].setSalemanId(goods[13]);
                    }

                    //id,name,address,phone (trade_user)
                    goods = argoods[1].split(g_split_val);
                    if (goods.length == 4) {
                        uisalemansearchSelect(goods);
                        g_pageobj['{_UID_}'].setSalemanId(goods[0]);
                    }

                    //contact_id,contact_name,contact_address,phone
                    goods = argoods[2].split(g_split_val);
                    if (goods.length == 4) {
                        uicontactsearchSelect(goods);
                        g_pageobj['{_UID_}'].setContactId(goods[0]);
                    }
                    //deploymentmans
                    goods = argoods[3].split(g_split_val);
                    if ((goods.length >= 3) && (goods.length % 3 == 0)) {
                        var i = 0;
                        while (i < goods.length) {
                            g_pageobj['{_UID_}'].deploymentManAdd(goods[i], goods[i + 1], goods[i + 2]);
                            i += 3;
                        }
                    }
                    for (var k = 4; k < argoods.length; k++) {
                        goods = argoods[k].split(g_split_val);
                        //goods_id,unit_id,unit,goods_name,unit_price,quantity,serial,warranty,discount,id_exim_invoice_details,color_name,template_id
                        if (goods.length >= 13) {
                            //trong 1 phieu co the 1 mat hang + 1 dvt xuat hien nhieu lan
                            var keyid = goods[0] + gIdCombineChar + goods[1];
                            for (var i = 0; i < g_pageobj['{_UID_}'].m_invoice_prd.length; i++) {
                                if (g_pageobj['{_UID_}'].m_invoice_prd[i].id == keyid) {
                                    keyid = keyid + "1";
                                }
                            }
                            var id_mixmain = goods[12];
                            var parent_id = "";
                            var pii = null;
                            //hang nguyen lieu, tim parent
                            if (id_mixmain > 0) {
                                for (var i = 0; i < g_pageobj['{_UID_}'].m_invoice_prd.length; i++) {
                                    if (g_pageobj['{_UID_}'].m_invoice_prd[i].extra_id == id_mixmain) {
                                        pii = g_pageobj['{_UID_}'].m_invoice_prd[i];
                                        parent_id = pii.id;
                                        break;
                                    }
                                }
                                if (pii == null) {
                                    showMsg(itxt("khongtimthaythanhphamcuanguyenlieu"));
                                    return;
                                }
                            }

                            var ii = new Object();
                            ii.id = keyid;
                            ii.goods_id = goods[0];
                            ii.unit_id = goods[1];
                            ii.name = goods[3];
                            ii.code = "";
                            ii.unit_name = goods[2];
                            ii.price = goods[4];
                            ii.quantity = goods[5];
                            ii.discount = goods[8];
                            ii.serial = goods[6];
                            ii.warranty = goods[7];
                            ii.color_name = goods[10];
                            ii.template_id = goods[11];
                            ii.parent_id = parent_id;
                            ii.extra_id = goods[9];
                            ii.quantity_max = 0;
                            ii.materials = null;

                            if (pii == null)
                                g_pageobj['{_UID_}'].m_invoice_prd[g_pageobj['{_UID_}'].m_invoice_prd.length] = ii;
                            else {
                                if (isEmpty(pii.materials)) pii.materials = new Array();
                                pii.materials[pii.materials.length] = ii;
                            }
                        }
                    }
                    g_pageobj['{_UID_}'].m_invoice_id = invoice_id;
                    g_pageobj['{_UID_}'].invoiceShow();
                    eleEnable("buttondeclare", true);
                    eleEnable("buttonsave", true);
                    eleEnable("buttonprint", true);
                    eleEnable("buttonnew", false);
                    eleEnable("buttondelivery", true);
                    eleEnable("buttondo", true);
                    hideModal();
                }
                else
                    showMsg(itxt("thatbai"), "NẠP PHIẾU");
            },
            error: function () {
                hideModal();
                showMsg(itxt("thatbai"), "NẠP PHIẾU");
            }
        });
        return false;
    },
    invoiceGoodsAddOrIncrease(goods_id, unit_id, goods_name, unit_name, export_price, color_name, template_id, parent_id, optional_extra_id, optional_quantity_max, fnCallBack) {
        for (i = 0; i < this.m_invoice_prd.length; i++) {
            if ((this.m_invoice_prd[i].goods_id == goods_id) && (this.m_invoice_prd[i].unit_id == unit_id)) {
                this.m_invoice_prd[i].quantity++;
                g_pageobj['{_UID_}'].invoiceShow();
                if (typeof fnCallBack !== "undefined") fnCallBack(1);
                return;
            }
        }
        g_pageobj['{_UID_}'].invoiceGoodsAdd(goods_id, unit_id, 1, goods_name, unit_name, export_price, color_name, template_id, parent_id, optional_extra_id, optional_quantity_max);
        if (typeof fnCallBack !== "undefined") fnCallBack(1);
    },
    //ds_goods_stock
    invoiceGoodsAddByCode: function (goods_code, fnCallBack) {
        var url = '?page=' + this.m_invoice_type + '&pagesub=goods_details&goods_code=' + uriEncode(goods_code) + "&store_id=" + getSelectVal("select_store_id");
        jQuery.ajax({
            url: url,
            data: "",
            type: "GET",
            success: function (data) {
                if (isDataOk(data)) {
                    var vals = getDataOk(data).split(g_split_val);
                    if (vals.length != ds_goods_stock.length) {
                        UiControl.inputTextGoodsCodeBarcodeShowImageStatus("idgoodscodewr", 2);
                        if (typeof fnCallBack !== "undefined") fnCallBack(0);
                        return;
                    }
                    g_pageobj['{_UID_}'].invoiceGoodsAddOrIncrease(vals[1], parseNumberVn(vals[2]), vals[3], vals[5], parseNumberVn(vals[7]), vals[8], vals[12], fnCallBack);
                    UiControl.inputTextGoodsCodeBarcodeShowImageStatus("idgoodscodewr", 0);
                }
                else {
                    UiControl.inputTextGoodsCodeBarcodeShowImageStatus("idgoodscodewr", 2);
                    if (typeof fnCallBack !== "undefined") fnCallBack(-1);

                }
            },
            error: function () {
                UiControl.inputTextGoodsCodeBarcodeShowImageStatus("idgoodscodewr", 2);
            }
        });
    },
    invoiceGoodsChange(idele, field_name, id, goods_id, unit_id) {
        //alert(field_name + ":" + idele.value + ":" + id + ":" + goods_id + "_" + unit_id);
        for (var i = 0; i < this.m_invoice_prd.length; i++) {
            if (this.m_invoice_prd[i].id == id) {

                var ii = this.m_invoice_prd[i];
                if (field_name == "quantity") {
                    if (parseNumberVn(ii.template_id) > 0) {
                        this.invoiceGoodsMaterialOnParentQuantity(ii, idele.value);
                    }
                    this.m_invoice_prd[i].quantity = parseNumberVn(idele.value);
                } else if (field_name == "price") {
                    this.m_invoice_prd[i].price = parseNumberVn(idele.value);
                } else if (field_name == "discount") {

                    this.m_invoice_prd[i].discount = parseNumberVn(idele.value);
                } else if (field_name == "serial") {
                    this.m_invoice_prd[i].serial = (idele.value);
                } else if (field_name == "color_name") {
                    this.m_invoice_prd[i].color_name = (idele.value);
                }
                this.invoiceShowSum();
                break;
            }
        }

    },
    invoiceGoodsClick: function (id, goods_id, unit_id) {
        if (!this.can_edit) return;
        for (var i = 0; i < this.m_invoice_prd.length; i++) {
            if (this.m_invoice_prd[i].id == id) {
                g_pageobj['{_UID_}'].menuPopupGoods(i);
                break;
            }
        }
    },
    invoiceGoodsAdd: function (goods_id, unit_id, quantity, goods_name, unit_name, export_price, color_name, template_id, parent_id, optional_extra_id, optional_quantity_max) {

        //phieunhaptralai
        if (parseNumberVn(optional_extra_id) > 0) {
            for (i = 0; i < this.m_invoice_prd.length; i++) {
                if (this.m_invoice_prd[i].extra_id == optional_extra_id) {
                    if (!isEmpty(optional_quantity_max) && (this.m_invoice_prd[i].quantity >= this.m_invoice_prd[i].quantity_max))
                        return;
                    this.m_invoice_prd[i].quantity++;
                    g_pageobj['{_UID_}'].invoiceShow();
                    return;
                }
            }
        }
        if (isEmpty(parent_id)) parent_id = "";
        if (parent_id == "0") parent_id = "";
        if (isEmpty(template_id)) template_id = "";
        //goods_id,unit_id,unit_name,goods_name,export_price,quantity,serial
        //trong 1 phieu co the 1 mat hang + 1 dvt xuat hien nhieu lan
        var keyid = goods_id.toString() + gIdCombineChar + unit_id.toString();
        for (i = 0; i < this.m_invoice_prd.length; i++) {
            if (this.m_invoice_prd[i].id == keyid) {
                keyid = keyid + "1";
            }
        }

        //tuan theo dung thu tu ds_goods_exim
        var ii = new Object();
        ii.id = keyid;
        ii.goods_id = goods_id;
        ii.unit_id = unit_id;
        ii.name = goods_name;
        ii.code = "";
        ii.unit_name = unit_name;
        ii.price = export_price;
        ii.quantity = quantity;
        ii.discount = 0;
        ii.serial = "";
        ii.warranty = 0;
        if (isEmpty(color_name))
            ii.color_name = "";
        else
            ii.color_name = color_name;
        ii.template_id = template_id;
        ii.parent_id = parent_id;
        if (isEmpty(optional_extra_id))
            ii.extra_id = 0;
        else
            ii.extra_id = optional_extra_id;

        if (isEmpty(optional_quantity_max))
            ii.quantity_max = 0;
        else
            ii.quantity_max = optional_quantity_max;
        ii.materials = null;
        this.m_invoice_prd[this.m_invoice_prd.length] = ii;
        if (ii.template_id > 0) {
            UiControl.inputTextGoodsCodeBarcodeShowImageStatus("idgoodscodewr", 1);
            this.invoiceGoodsAdd_Mixed(ii);
        }

        this.invoiceShow();
    },
    //id_divshow,id, goods_id, unit_id..
    invoiceGoodsExpand: function (iddivshow, id, goods_id, unit_id) {
        var ii = null;
        var prds = g_pageobj["{_UID_}"].m_invoice_prd;
        if (isEmpty(prds)) return;
        for (var i = 0; i < prds.length; i++) {

            if (prds[i].id == id) {
                ii = prds[i];
                break;
            }
        }
        if (isEmpty(ii)) {

            showMsg(itxt("khongtimthay"));
            return;
        }
        if (!Array.isArray(ii.materials)) return;
        var html = "";
        for (var i = 0; i < ii.materials.length; i++) {
            var cii = ii.materials[i];
            html += "<div class='list_item'>";
            html += "<div class='gridcell' style='width:65%;float:left;' onclick='event.stopPropagation();g_pageobj[\"{_UID_}\"].invoiceGoodsMaterialClick(\"" + ii.id + "\",\"" + cii.id + "\");'>" + cii.name + "</div>";
            html += "<div class='gridcell padding0' style='width:8%;'>";
            html += "<input onchange='g_pageobj[\"{_UID_}\"].invoiceGoodsMaterialChange(this,\"quantity\",\"" + ii.id + "\",\"" + cii.id + "\");' type='text' onfocus='this.select();' class='asdivcell_input' style='text-align:right;' onclick='event.stopPropagation();' value='" + cii.quantity + "'>";
            html += "</div>";
            html += "<div class='gridcell padding0' style='width:17%;' onclick='event.stopPropagation();'>";
            html += "<input onchange='g_pageobj[\"{_UID_}\"].invoiceGoodsMaterialChange(this,\"serial\",\"" + ii.id + "\",\"" + cii.id + "\");' type='text' onfocus='this.select();' placeholder='" + ds_goods_exim[9].head + "' class='asdivcell_input' style='text-align:right;' onclick='event.stopPropagation();' value='" + cii.serial + "'>";
            html += "</div>";
            html += "<div class='gridcell padding0' style='width:10%;' onclick='event.stopPropagation();'>";
            html += "<input onchange='g_pageobj[\"{_UID_}\"].invoiceGoodsMaterialChange(this,\"color_name\",\"" + ii.id + "\",\"" + cii.id + "\");' type='text' onfocus='this.select();' placeholder='" + ds_goods_exim[12].head + "' class='asdivcell_input' style='text-align:right;' onclick='event.stopPropagation();' value='" + cii.color_name + "'>";
            html += "</div>";
            html += "</div>";
        }

        setInnerById(iddivshow, html);
    },
    invoiceGoodsMaterialOnParentQuantity: function (ii, newquantity) {
        if (ii.quantity == 0) return false;
        var ratio = (newquantity / ii.quantity);
        if (Array.isArray(ii.materials)) {
            for (var i = 0; i < ii.materials.length; i++) {
                ii.materials[i].quantity *= ratio;
            }
        }
        var idrowmain = gridViewEx.getRowIdMainCollapsiable(ii.id);
        var idrowsub = gridViewEx.getRowIdSubCollapsiable(ii.id);
        this.invoiceGoodsExpand(idrowsub, ii.id, ii.goods_id, ii.unit_id);
    },

    invoiceGoodsMaterialSwitchDone: function (pid, cid, id, goods_id, unit_id, tenhang, mahang, dvt, ton, dongia, mausac, mausacid, kichthuoc, anh, template_id) {
        if (template_id > 0) {
            showMsg(itxt("khonghotrodoithanhhangtohopcombo"));
            return;
        }
        var pii = null;
        var prds = g_pageobj["{_UID_}"].m_invoice_prd;
        if (isEmpty(prds)) {
            showModal(itxt("khongcohang"));
            return;
        }
        for (var i = 0; i < prds.length; i++) {
            if (prds[i].id == pid) {
                pii = prds[i];
                break;
            }
        }
        if (isEmpty(pii)) {
            showMsg(itxt("khongtimthayhang"));
            return;
        }

        if (!Array.isArray(pii.materials)) return;

        for (var j = 0; j < pii.materials.length; j++) {
            if (pii.materials[j].id == cid) {
                var cii = pii.materials[j];
                var idrowsub = gridViewEx.getRowIdSubCollapsiable(pii.id);//old_id
                cii.id = cii.id + goods_id + gIdCombineChar + unit_id;
                cii.goods_id = goods_id;
                cii.unit_id = unit_id;
                cii.name = tenhang;
                cii.code = mahang;
                cii.unit_name = dvt;
                cii.price = dongia;
                //cii.quantity = ;
                //cii.discount = vals[8];
                cii.serial = "";
                //cii.warranty = vals[10];
                cii.extra_id = "";
                cii.color_name = mausac;
                cii.template_id = template_id;
                //cii.parent_id = ;
                //cii.quantity_max = ;
                //cii.materials = null;

                this.invoiceGoodsExpand(idrowsub, pii.id, pii.goods_id, pii.unit_id);
                break;
            }
        }
    },
    invoiceGoodsMaterialSwitch: function (parent_id, id) {
        //DlgSelect.showGoods(1, 'uigoodssearchCmd_Done', null, null, 1, getValById("select_store_id"), null, null, g_pageobj['{_UID_}'].m_invoice_type);
        DlgSelect.showGoods(1, "g_pageobj['{_UID_}'].invoiceGoodsMaterialSwitchDone", [parent_id, id], "", 1, getValById("select_store_id"), null, null, g_pageobj["{_UID_}"].m_invoice_type);
    },

    invoiceGoodsMaterialClick: function (parent_id, id) {
        var menu = "";
        menu += "<a href='javascript:void(0)' onclick=\"hideModal();javascript:g_pageobj['{_UID_}'].invoiceGoodsMaterialSwitch('" + parent_id + "','" + id + "')\" class='menu_popup_item'>Đổi nguyên liệu/thành phần" + "</a>";
        menu += "<a href='javascript:void(0)' onclick=\"hideModal();javascript:g_pageobj['{_UID_}'].invoiceGoodsMaterialRemove('" + parent_id + "','" + id + "')\" class='menu_popup_item'>Xóa nguyên liệu/thành phần" + "</a>";
        showModal(menu, itxt("nguyenlieuthanhphan"));
    },
    invoiceGoodsMultiSerialDo: function (serials, index) {
        if (index >= g_pageobj["{_UID_}"].m_invoice_prd.length)
            return;
        var ii = g_pageobj["{_UID_}"].m_invoice_prd[index];
        serials = serials.replaceAll(" ", ",");
        serials = serials.replaceAll("\r", ",");
        serials = serials.replaceAll("\n", ",");
        while (serials.indexOf(",,") >= 0) serials = serials.replaceAll(",,", ",");
        if (serials.left(1) == ",") serials = serials.right(serials.length - 1);
        if (serials.right(1) == ",") serials = serials.left(serials.length - 1);
        var vals = serials.split(",");
        ii.quantity = vals.length;
        ii.serial = serials;
        g_pageobj["{_UID_}"].invoiceShow();
    },
    invoiceGoodsMultiSerial: function (index) {
        if (index >= this.m_invoice_prd.length)
            return;
        var ii = this.m_invoice_prd[index];
        DlgGetText("Nhập vào serial, các serial ngăn cách bằng khoảng trắng/dấy phẩy/xuống dòng",
            "g_pageobj[\'{_UID_}\'].invoiceGoodsMultiSerialDo", [index], false, ii.serial, 10);
    },
    invoiceGoodsMaterialChange: function (control, field_name, parent_id, id) {

        var ii = null;
        var prds = g_pageobj["{_UID_}"].m_invoice_prd;
        if (isEmpty(prds)) return;
        for (var i = 0; i < prds.length; i++) {
            if (prds[i].id == parent_id) {
                ii = prds[i];
                break;
            }
        }
        if (isEmpty(ii)) {
            showMsg(itxt("khongtimthay"));
            return;
        }

        var cii = null;
        if (!Array.isArray(ii.materials)) {
            showMsg(itxt("khongconguyenlieu"));
            return;
        }
        for (var i = 0; i < ii.materials.length; i++) {
            if (ii.materials[i].id == id) {
                cii = ii.materials[i];
                break;
            }
        }

        if (isEmpty(cii)) {
            showMsg(itxt("khongtimthay"));
            return;
        }
        if (field_name == "quantity") {
            cii.quantity = control.value;
        } else if (field_name == "serial") {
            cii.serial = control.value;
        } else if (field_name == "color_name") {
            cii.color_name = control.value;
        } else {
            showMsg(itxt("khongxacdinhthuoctinh"));
        }
    },
    invoiceGoodsAdd_Mixed: function (ii) {
        //ii.id, ii.goods_id, ii.unit_id, ii.template_id
        if (!isEmpty(ii.materials)) {
            if (ii.materials.length > 0)
                return;
        }

        var url = '?page=' + this.m_invoice_type + '&pagesub=goods_materials&goods_id=' + ii.goods_id + "&unit_id=" + ii.unit_id + "&template_id=" + ii.template_id;
        jQuery.ajax({
            url: url,
            data: "",
            type: "GET",
            success: function (data) {
                if (!isDataOk(data)) {
                    UiControl.inputTextGoodsCodeBarcodeShowImageStatus("idgoodscodewr", 2);
                    return;
                }
                data = getDataOk(data);
                if (data.length < 1) return;
                var prds = data.split(g_split_row);
                if (prds.length < 1) return;

                ii.materials = new Array();
                for (var i = 0; i < prds.length; i++) {
                    var vals = prds[i].split(g_split_val);
                    if (vals.length != ds_goods_exim.length) continue;
                    //ds_goods_exim
                    //hang load theo template (co label) nen co the co thanh phan mau chua xac dinh hang, goods_id=0
                    var keyid = ii.id + gIdCombineChar + vals[1] + gIdCombineChar + vals[2] + gIdCombineChar + i;
                    var cii = new Object();
                    cii.id = keyid;
                    cii.goods_id = vals[1];
                    cii.unit_id = vals[2];
                    cii.name = vals[3];
                    cii.code = vals[4];
                    cii.unit_name = vals[5];
                    cii.price = vals[6];
                    cii.quantity = vals[7];
                    cii.discount = vals[8];
                    cii.serial = "";
                    cii.warranty = vals[10];
                    cii.extra_id = "";
                    cii.color_name = vals[12];
                    cii.template_id = vals[13];
                    cii.parent_id = ii.id;
                    cii.quantity_max = vals[15];
                    cii.materials = null;
                    ii.materials[ii.materials.length] = cii;
                }
                UiControl.inputTextGoodsCodeBarcodeShowImageStatus("idgoodscodewr", 0);
            },
            error: function () {
                UiControl.inputTextGoodsCodeBarcodeShowImageStatus("idgoodscodewr", 2);
            }
        });
    },
    invoiceGoodsRemoveById: function (id) {
        for (var i = 0; i < this.m_invoice_prd.length; i++) {
            if (this.m_invoice_prd[i].id == id) {
                g_pageobj['{_UID_}'].invoiceGoodsRemove(i);
                break;
            }
        }
    },
    //index<0: removeAll
    invoiceGoodsRemove: function (index) {
        var nMax = this.m_invoice_prd.length - 1;
        if (index < 0) {
            for (var i = nMax; i >= 0; i--) {
                ii = this.m_invoice_prd.splice(i, 1);
                delete ii; ii = null;
            }
            this.invoiceShow();
            return;
        }

        if (index >= this.m_invoice_prd.length)
            return;
        var ii = this.m_invoice_prd[index];
        var id = ii.id;
        for (var i = nMax; i >= 0; i--) {
            ii = this.m_invoice_prd[i];
            if ((ii.parent_id == id) || (ii.id == id)) {
                ii = this.m_invoice_prd.splice(i, 1);
                delete ii; ii = null;
            }
        }
        this.invoiceShow();
    },
    invoiceGoodsSerialChange: function (index) {
        if (index < 0)
            return;
        if (index >= this.m_invoice_prd.length)
            return;
        var serialid = "serial" + index;
        inputserial = document.getElementById(serialid);
        var serial = inputserial.value;
        this.m_invoice_prd[index].serial = serial;
    },
    invoiceGoodsChangeColor: function (index) {

        DlgSelect.showGoodsColor("g_pageobj['{_UID_}'].invoiceGoodsChangeColorDo", new Array(index.toString()));

    },
    invoiceGoodsChangeColorDo: function (index, color_id, color_name, short_name) {
        hideModalBlock();

        if (index < 0)
            return;
        if (index >= this.m_invoice_prd.length)
            return;
        if (index < 0) {
            showModal("Lỗi. Không tìm thấy hàng");
            return;
        }
        var ii = this.m_invoice_prd[index];
        ii.color_name = color_name;
        this.invoiceShow();
    },
    invoiceGoodsSwitchDone: function (index, id, goods_id, unit_id, tenhang, mahang, dvt, ton, dongia, mausac, mausacid, kichthuoc, anh, template_id) {
        if (index < 0)
            return;
        if (index >= this.m_invoice_prd.length)
            return;
        if (index < 0) {
            showMsg([itxt("loi"), itxt("khongtimthayhang")], "", 1000);
            return;
        }
        var cii = this.m_invoice_prd[index];
        var idold = cii.id;
        //cii.id = cii.id + gIdCombineChar + id; //=> khong can thiet doi vi no van la duy nhat, doi se mat onclick

        cii.goods_id = goods_id;
        cii.unit_id = unit_id;
        cii.name = tenhang;
        cii.code = mahang;
        cii.unit_name = dvt;
        cii.price = dongia;
        //cii.quantity = ;
        //cii.discount = vals[8];
        cii.serial = "";
        //cii.warranty = vals[10];
        cii.extra_id = "";
        cii.color_name = mausac;
        cii.template_id = template_id;
        cii.parent_id = "";
        cii.quantity_max = 0;
        cii.materials = null;
        gridViewEx.showGridUpdateable_UpdateCell(idold, cii, "name");
        gridViewEx.showGridUpdateable_UpdateCell(idold, cii, "unit_name");
        if (cii.template_id > 0) {
            UiControl.inputTextGoodsCodeBarcodeShowImageStatus("idgoodscodewr", 1);
            this.invoiceGoodsAdd_Mixed(cii);
        }
    },
    invoiceGoodsSwitch: function (index) {
        DlgSelect.showGoods(1, "g_pageobj[\"{_UID_}\"].invoiceGoodsSwitchDone", [index], "", 1, getValById("select_store_id"), null, null, g_pageobj['{_UID_}'].m_invoice_type);
    },
    menuPopupGoods: function (index) {
        if (index < 0)
            return;
        if (index >= this.m_invoice_prd.length)
            return;
        if (index < 0) {
            showMsg([itxt("loi"), itxt("khongtimthayhang")], "", 1000);
            return;
        }
        var ii = this.m_invoice_prd[index];
        var menu = "";
        if ((this.m_invoice_type != "phieunhaptralai") && (this.m_invoice_type != "phieuxuattralai"))
            menu += "<a href='javascript:void(0)' onclick=\"hideModal();javascript:g_pageobj['{_UID_}'].invoiceGoodsSwitch(" + index + ")\" class='menu_popup_item'>Đổi hàng khác" + "</a>";
        menu += "<a href='javascript:void(0)' onclick=\"hideModal();javascript:g_pageobj['{_UID_}'].invoiceGoodsMultiSerial(" + index + ")\" class='menu_popup_item serial w50'>" + itxt("menu_nhapnhieuserial") + "</a>";
        menu += "<a href='javascript:void(0)' onclick='javascript:mShowGoodsEximDetails(1," + getValById("select_store_id") + "," + ii.goods_id + "," + ii.unit_id + ",\"\")' class='menu_popup_item w50'>" + itxt("xemnhapxuat") + "</a>";
        menu += "<a href='javascript:void(0)' onclick='javascript:mShowGoodsEximDetails(1," + getValById("select_store_id") + "," + ii.goods_id + "," + ii.unit_id + ",\"xb\")' class='menu_popup_item w50'>" + itxt("chitietxuat") + "</a>";
        menu += "<a href='javascript:void(0)' onclick='javascript:mShowGoodsEximDetails(1," + getValById("select_store_id") + "," + ii.goods_id + "," + ii.unit_id + ",\"nm\")' class='menu_popup_item w50'>" + itxt("chitietnhap") + "</a>";
        menu += "<a href='javascript:void(0)' onclick=\"hideModal();javascript:g_pageobj['{_UID_}'].invoiceGoodsRemove(" + index + ")\" class='menu_popup_item remove'>" + itxt("loaihang") + "</a>";
        showModal(menu, ii.name);
    },
    invoiceShow: function () {
        var bhideprice = false;
        if ((this.m_invoice_type == "phieuxuatchuyenkho") || (this.m_invoice_type == "phieunhapchuyenkho")) {
            bhideprice = true;
            //this.data_struct["price"].visible=0;
        }
        gridViewEx.showGridUpdateable(this.m_invoice_prd, "idinvoicegoodslistex",
            'g_pageobj["{_UID_}"].invoiceGoodsChange', 'g_pageobj["{_UID_}"].invoiceGoodsClick',
            'g_pageobj["{_UID_}"].invoiceGoodsExpand');
        if ((this.m_invoice_type == "phieuxuatchuyenkho") || (this.m_invoice_type == "phieunhapchuyenkho"))
            return;
        if (typeof showDeploymentMan !== "undefined") {
            showDeploymentMan();
            // safe to use the function
        }

        this.invoiceShowSum();
    },
    invoiceShowSum: function () {
        var sum = this.invoiceGetSum();
        invoice_sum = document.getElementById("invoice_sum");
        if (isEmpty(invoice_sum)) return;
        invoice_sum.value = formatNumber(sum, true);
        this.invoiceCalc();
    },
    invoiceGetSum: function () {
        var sum = 0;
        for (i = 0; i < this.m_invoice_prd.length; i++) {

            if (!isEmpty(this.m_invoice_prd[i].parent_id)) continue;
            sum += this.m_invoice_prd[i].quantity * this.m_invoice_prd[i].price * (1 - this.m_invoice_prd[i].discount / 100);
        }
        var invoice_moneyrate = document.getElementById("invoice_moneyrate");
        if (invoice_moneyrate === null) { invoice_moneyrate = 0; } else invoice_moneyrate = invoice_moneyrate.value;
        return sum;
    },
    invoiceGetRawData: function () {
        var data = "";
        for (i = 0; i < this.m_invoice_prd.length; i++) {
            var ii = this.m_invoice_prd[i];
            if (data.length > 0)
                data += g_split_row;
            data += ii.id + g_split_val;
            data += ii.parent_id + g_split_val;
            data += ii.goods_id + g_split_val;
            data += ii.unit_id + g_split_val;
            data += formatNumber(ii.quantity) + g_split_val;
            data += formatNumber(ii.price) + g_split_val;
            data += uriEncode(ii.serial) + g_split_val;
            data += uriEncode(ii.color_name) + g_split_val;
            data += ii.extra_id + g_split_val;
            data += formatNumber(ii.discount);
            if (Array.isArray(ii.materials)) {
                for (var j = 0; j < ii.materials.length; j++) {
                    var cii = ii.materials[j];
                    data += g_split_row;
                    data += cii.id + g_split_val;
                    data += cii.parent_id + g_split_val;
                    data += cii.goods_id + g_split_val;
                    data += cii.unit_id + g_split_val;
                    data += formatNumber(cii.quantity) + g_split_val;
                    data += formatNumber(cii.price) + g_split_val;
                    data += uriEncode(cii.serial) + g_split_val;
                    data += uriEncode(cii.color_name) + g_split_val;
                    data += cii.extra_id + g_split_val;
                    data += formatNumber(cii.discount);
                }
            }
        }
        return data;
    },
    invoiceCalc: function () {
        var invoice_sum = parseNumberVn(getValById("invoice_sum"));
        var invoice_vat = parseNumberVn(getValById("invoice_vat"));
        var invoice_discount = parseNumberVn(getValById("invoice_discount"));
        var invoice_debit = parseNumberVn(getValById("invoice_debit"));
        var invoice_money_discount = parseNumberVn(getValById("invoice_money_discount"));

        var mustreceipt = invoice_sum * (1 - invoice_discount / 100) * (1 + invoice_vat / 100) - invoice_money_discount;

        setValById("invoice_sumreal", formatNumber(mustreceipt, true));
        //default:pay or debit

        if (typeof (g_paymentdebit) === "undefined") {
            setValById("invoice_pay", formatNumber(mustreceipt - invoice_debit, true));
            setValById("invoice_debit", "");
        }
        else {
            setValById("invoice_pay", "");
            setValById("invoice_debit", formatNumber(mustreceipt, true));
        }

    },
    invoiceCalcPayDebt: function (ischangefrompay) {
        var invoice_sumreal = document.getElementById("invoice_sumreal");
        var invoice_pay = document.getElementById("invoice_pay");
        var invoice_debit = document.getElementById("invoice_debit");
        if (ischangefrompay) {
            invoice_debit.value = formatNumber(parseNumberVn(invoice_sumreal.value) - parseNumberVn(invoice_pay.value));
        }
        else {
            invoice_pay.value = formatNumber(parseNumberVn(invoice_sumreal.value) - parseNumberVn(invoice_debit.value));
        }
    },
    invoiceCheckValidQuantity: function () {
        var i = 0;
        if (this.m_invoice_prd.length < 1) {
            showModal(itxt("phieukhongcohang"));
            return false;
        }
        //check serial tuong ung so luong
        for (i = 0; i < this.m_invoice_prd.length; i++) {
            if (this.m_invoice_prd[i].serial.toString().length > 0) {
                if (this.m_invoice_prd[i].quantity <= 0) {
                    showMsg(itxt("soluongphaituongungvoisoserial") + "<p>" + this.m_invoice_prd[i].name + "</p>");
                    return false;
                }
                var ss = this.m_invoice_prd[i].serial.toString().split(",");
                if (ss.length != this.m_invoice_prd[i].quantity) {
                    showMsg(itxt("soluongphaituongungvoisoserial") + "<p>" + this.m_invoice_prd[i].name + "</p>");
                    return false;
                }
            }
        }
        //
        if (this.m_invoice_type == "phieunhaptralai") {
            for (i = 0; i < this.m_invoice_prd.length; i++) {
                if (!isEmpty(this.m_invoice_prd[i].quantity_max)) {
                    if (this.m_invoice_prd[i].quantity > this.m_invoice_prd[i].quantity_max) {
                        showMsg("<b>" + this.m_invoice_prd[i].name + "</b>: " + itxt("soluongvuotquamucchophep") + "(" + this.m_invoice_prd[i].quantity + ">" + this.m_invoice_prd[i].quantity_max + ")");
                        return false;
                    }
                }
            }
        }
        return true;
    },
    invoiceSave: function () {
        if (!this.invoiceCheckValidQuantity())
            return false;
        var buttonsave = document.getElementById("buttonsave");
        if (isObject(buttonsave)) buttonsave.disabled = true;

        var store_id = getSelectVal("select_store_id");
        var ncontactname = document.getElementById("ncontactname");
        var ncontactcomment = document.getElementById("ncontactcomment");
        var ncontactaddress = document.getElementById("ncontactaddress");
        var ncontactphone = document.getElementById("ncontactphone");
        var store_id_swap = document.getElementById("store_id_swap");
        var invoice_id_swap = document.getElementById("invoice_id_swap");
        var invoice_date = document.getElementById("invoice_date");

        var sncontactname = "", sncontactcomment = "", sncontactaddress = "", sncontactphone = "";
        if (ncontactname === null) { } else sncontactname = ncontactname.value;
        if (ncontactcomment === null) { } else sncontactcomment = ncontactcomment.value;
        if (ncontactaddress === null) { } else sncontactaddress = ncontactaddress.value;
        if (ncontactphone === null) { } else sncontactphone = ncontactphone.value;
        if (store_id_swap === null) { } else store_id_swap = store_id_swap.value;
        if (invoice_id_swap === null) { } else invoice_id_swap = invoice_id_swap.value;

        //phieunhapchuyenkho&phieuxuatchuyenkho
        if ((this.m_invoice_type == "phieuxuatchuyenkho")) {
            if (parseInt(store_id) == parseInt(store_id_swap)) {
                showMsg(itxt("khoxuatvakhonhapphaikhacnhau"))
                if (isObject(buttonsave)) buttonsave.disabled = false;
                return;
            }
        }


        var invoice_discount = getValById("invoice_discount");
        var invoice_money_discount = getValById("invoice_money_discount");
        var invoice_debit = getValById("invoice_debit");
        var invoice_sum = getValById("invoice_sum");
        var invoice_vat = getValById("invoice_vat");
        var invoice_comment = getValById("invoice_comment");
        var invoice_bankaccount = getSelectVal("invoice_bankaccount");
        var card_money = getValById("card_money");
        var card_code = getValById("card_code");
        if (isNaN(this.m_contact_id)) {

            showMsg(itxt("chuachondoitac"));
            if (isObject(buttonsave)) buttonsave.disabled = false;
            return;
        }
        if (isNaN(store_id)) {
            showModal("Chưa xác định kho hàng");
            if (isObject(buttonsave)) buttonsave.disabled = false;
            return;
        }
        if (isNaN(this.m_saleman_id)) this.m_saleman_id = 0;

        sncontactname = uriEncode(sncontactname);
        sncontactcomment = uriEncode(sncontactcomment);
        sncontactaddress = uriEncode(sncontactaddress);
        sncontactphone = uriEncode(sncontactphone);
        invoice_comment = uriEncode(invoice_comment);
        //deployment man
        var depman_ids = "";
        if (!isEmpty(this.m_deploymentmans)) {
            for (var i = 0; i < this.m_deploymentmans.length; i++) {
                if (depman_ids.length > 0) depman_ids += g_split_val;
                depman_ids += this.m_deploymentmans[i][0];
            }
        }
        var url = '?page=' + this.m_invoice_type + '&pagesub=invoice_save&invoice_type=' + this.m_invoice_type +
            '&invoice_discount=' + invoice_discount + '&invoice_money_discount=' + invoice_money_discount +
            '&card_code=' + card_code + '&card_money=' + card_money +
            '&ncontactname=' + sncontactname + '&invoice_vat=' + invoice_vat + '&invoice_comment=' + invoice_comment +
            '&ncontactcomment=' + sncontactcomment + '&ncontactaddress=' + sncontactaddress + '&ncontactphone=' + sncontactphone +
            '&invoice_debit=' + invoice_debit + '&contact_id=' + this.m_contact_id + '&store_id=' + store_id +
            '&store_id_swap=' + store_id_swap + '&invoice_id_swap=' + invoice_id_swap +
            '&bank_account=' + invoice_bankaccount +
            '&invoice_id=' + this.m_invoice_id +
            '&invoice_date=' + invoice_date.value +
            '&saleman_id=' + this.m_saleman_id +
            '&depman_ids=' + depman_ids +
            '&data=' + this.invoiceGetRawData();

        showWaitModal(1);
        var dataString = "";
        jQuery.ajax({
            url: url,
            data: dataString,
            type: "GET",
            success: function (data) {

                if (!isDataOk(data)) {
                    showMsg([itxt("loi"), getDataFail(data)]);
                    if (isObject(buttonsave)) buttonsave.disabled = false;
                    return;
                }
                hideModalBlock();
                g_pageobj['{_UID_}'].invoiceSaveDone(data);//value=ok+id
            },
            error: function () {
                showMsg(itxt("loi"));
            }
        });
    },
    invoiceClear: function () {
        var id = document.getElementById("pageheader" + this.m_uid);
        if (id != null) {
            var header = id.innerHTML;
            header = header.replace(" [SỬA]", "");
            id.innerHTML = header;
        }
        //var key="edit"+this.m_invoice_type+this.m_invoice_id;
        //g_data[key]=null;
        g_data[this.m_invoice_prd_index + "canedit"] = null;
        g_data[this.m_invoice_prd_index + "salemanid"] = null;
        g_data[this.m_invoice_prd_index + "contactid"] = null;
        delete g_data[this.m_invoice_prd_index + "deploymentmans"];
        g_data[this.m_invoice_prd_index + "deploymentmans"] = null;
        g_data[this.m_invoice_prd_index + "invoiceid"] = null;

        this.m_invoice_id = 0;
        while (this.m_invoice_prd.length > 0) {
            var ii = this.m_invoice_prd.splice(0, 1);
            ii = null;
            delete ii;
        }
        delete g_data[this.m_invoice_prd_index];
        g_data[this.m_invoice_prd_index] = null;
        this.m_invoice_prd = null;

        gridViewEx.showGridUpdateable("", "idinvoicegoodslistex");

        setValById("invoice_vat", "");
        setValById("invoice_discount", "");
        setValById("invoice_sum", "");
        setValById("invoice_sumreal", "");
        setValById("invoice_pay", "");
        setValById("invoice_debit", "");
        setValById("invoice_bankaccount", "0");
        setValById("invoice_comment", "");
        setValById("", "");

        this.m_saleman_id = 0;
        this.m_contact_id = 0;
        this.m_deploymentmans = [];
        if (typeof uicontactsearch !== 'undefined')
            uicontactsearch.onClearSelect();

        if (typeof uisalemansearch !== 'undefined')
            uisalemansearch.onClearSelect();

        if (typeof uigoodssearch !== 'undefined')
            uigoodssearch.onClearSelect();
    },
    invoiceNew: function (invoice_type)//invoice_type:phieuxuatlequay,phieuxuatle,phieuxuatbuon
    {
        this.invoiceClear();
        eleEnable("buttondeclare", true);
        eleEnable("buttonsave", true);
        eleEnable("buttonprint", false);
        eleEnable("buttonnew", false);
        eleEnable("buttondelivery", false);
        eleEnable("buttondo", false);
        uicontactsearch.disabled = false;
        uigoodssearch.disabled = false;
        this.can_edit = true;
        g_data[this.m_invoice_prd_index + "canedit"] = true;
        if (!isEmpty(invoice_type))
            this.m_invoice_type = invoice_type;
        g_data[this.m_invoice_prd_index] = new Array();
        this.m_invoice_prd = g_data[this.m_invoice_prd_index];
    },
    //type:phieuxuatlequay,phieuxuatle,phieuxuatbuon
    invoicePrint: function () {
        if (this.m_invoice_id == 0) {
            showMsg(itxt("chuacophieu"), "", 1000);
            return;
        }
        if (g_invoicePrintType.size < 3) {
            showWaitModal(1, 0, itxt("xacdinhthietlapcogiay"));
            var url = "?page=list&pagesub=print_invoicesize";

            var dataString = "";
            jQuery.ajax({
                url: url,
                data: dataString,
                type: "GET",
                success: function (data) {
                    if (!isDataOk(data)) {
                        showMsg([itxt("loi"), getDataFail(data)], itxt("xacdinhthietlapcogiay"));
                        return;
                    }
                    data = getDataOk(data);
                    if (data.length < 1) {
                        showMsg([itxt("loi"), data], itxt("xacdinhthietlapcogiay"));
                        return;
                    }
                    var vals = data.split(g_split_val);
                    var i = 0;
                    while (i < (vals.length - 1)) {
                        g_invoicePrintType.set(vals[i], vals[i + 1]);
                        i += 2;
                    }
                    hideModalBlock();
                    if (g_invoicePrintType.size > 0) {
                        g_pageobj['{_UID_}'].invoicePrint();
                    } else {
                        showMsg(itxt("kichthuocgiayinkhongxacdinh"));
                    }
                },
                error: function () {
                    showMsg(itxt("loi"));
                }
            });
        } else {
            var size;
            if ((this.m_invoice_type != "phieuxuatlequay") && (this.m_invoice_type != "phieuxuatle") && (this.m_invoice_type != "phieuxuatbuon"))
                size = g_invoicePrintType.get("phieuxuatle");
            else
                size = g_invoicePrintType.get(this.m_invoice_type);
            //khong thuoc 1 trong phieu co ban

            if ((size != "k5880") && (size != "a4") && (size != "a5")) {
                showMsg(itxt("kichthuocgiayinkhongxacdinh") + ": " + size);
                return;
            }

            printInvoice(this.m_invoice_type.toLowerCase().indexOf("xuat") >= 0, this.m_invoice_id, size);
        }

    },
    invoiceSaveDone: function (ret) {
        this.can_edit = false;
        var buttonsave = document.getElementById("buttonsave");
        if (isDataOk(ret)) {
            this.m_invoice_id = parseInt(getDataOk(ret));
            g_data[this.m_invoice_prd_index + "invoiceid"] = this.m_invoice_id;

            eleEnable("buttondeclare", false);
            eleEnable("buttonsave", false);
            eleEnable("buttonprint", true);
            eleEnable("buttonnew", !this.m_invoice_editmode);
            eleEnable("buttondelivery", true);
            eleEnable("buttondo", true);
            uicontactsearch.disabled = true;
            uigoodssearch.disabled = true;
            showMsg("Đã ghi phiếu", "", 500);
        }
        else {
            this.m_invoice_id = 0;
            g_data[this.m_invoice_prd_index + "invoiceid"] = null;
            if (isObject(buttonsave)) buttonsave.disabled = false;
            showMsg([itxt("khongghiduocphieu"), getDataFail(ret)]);
        }
        if (this.m_invoice_type == "phieuxuatlequay") {
            if (m_print_sessionendauto == "1") {
                this.invoicePrint();
            }
        }
    },
};

//EMPLOYEE////////////////////////
function uisalemansearchGetData(idinput) {
    var search_key = uriEncode(getValById(idinput));
    var url = "?page=list&pagesub=employee&invoice_type=" + g_pageobj['{_UID_}'].m_invoice_type + "&name=" + search_key;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataFail(data)) {
                showMsg(getDataFail(data));
                return;
            }
            else if (isDataOk(data)) {
                data = getDataOk(data);
                var rows = data.split(g_split_row);
                var dataset = [];
                for (i = 0; i < rows.length; i++) {
                    if (rows[i].substr(0, g_sign_columnconfig.length) == g_sign_columnconfig)
                        continue;
                    if (rows[i].substr(0, g_sign_pageconfig.length) == g_sign_pageconfig)
                        continue;
                    dataset[dataset.length] = rows[i];
                }
                uisalemansearch.showList(dataset, false);
                showWaitStatus();
            }
            else
                showMsg(itxt("loi"));
            showWaitStatus();
        },
        error: function () {
            showMsg(itxt("loi"));
            showWaitStatus();
        }
    });
}
function uisalemansearchGetDataEx() {

}
function uisalemansearchGetDataEx_Done(id, name, address, phone) {

}

//id,name,address,phone
function uisalemansearchSelect(vals) {
    if (vals.length != 4) {
        showMsg("dulieuloi");
        return;
    }
    g_pageobj['{_UID_}'].setSalemanId(vals[0]);
    setValById(uisalemansearch.idinput, vals[1]);
}

var uisalemansearch = new UIListBoxEx("uisalemansearch",
    [
        { "name": "id", "head": "", visible: 0 },
        { "name": "name", "head": "Tên", visible: 1, "width": "100%", subinfo: [2, 3] },
        { "name": "address", "head": "Địa chỉ", visible: 0 },
        { "name": "phone", "head": "Điện thoại", visible: 0 },
    ]
);

uisalemansearch.icon = "imgs/salesman.png";
uisalemansearch.combobox_mode = false;
uisalemansearch.label_place_holder = "(kinh doanh)";
uisalemansearch.onGetData = "uisalemansearchGetData";
uisalemansearch.onCmd = "";
uisalemansearch.onSelect = "uisalemansearchSelect";
uisalemansearch.onSelectM = "";
uisalemansearch.show("idsaleman");

//goods search
//id,goods_id,unit_id,tenhang,mahang,dvt,ton,dongia,mausac,mausacid,kichthuoc,anh
/*
var ds_goods_stock = [
    { name: "id", head: "", visible: 0, type: "text" },
    { name: "goods_id", head: "", visible: 0 },
    { name: "unit_id", head: "", visible: 0 },
    { name: "tenhang", head: "Tên hàng", visible: 1, type: "text", required: 1, merge: 1, subinfo: [7, 5], width: "60%" },
    { name: "mahang", head: "Mã hàng", visible: 0, type: "text", required: 0, merge: 1 },
    { name: "dvt", head: "ĐVT", visible: 0, type: "text", required: 0, subinfobreak: "/" },
    { name: "ton", head: "Tồn", visible: 1, type: "number", required: 1, editable: 0, width: "20%" },
    { name: "dongia", head: "Đơn giá", visible: 0, type: "number", required: 0, editable: 1 },
    { name: "mausac", head: "Màu sắc", visible: 1, type: "text", required: 0, editable: 0, width: "20%", class: "divcell_color" },
    { name: "mausacid", head: "", visible: 0, type: "text", required: 0, editable: 0 },
    { name: "kichthuoc", head: "Kích thước", visible: 0, type: "text", required: 0, editable: 0 },
    { name: "anh", head: "Hình ảnh", visible: 0, type: "text", required: 0, editable: 0 },
    { name: "template_id", head: "", visible: 0, type: "number", required: 0, editable: 0 },
];
*/

var uigoodssearch = new UIListBoxEx("uigoodssearch", ds_goods_stock);
uigoodssearch.label_place_holder = "(" + itxt("nhaptenhang") + ")";
uigoodssearch.onGetData = "uigoodssearchGetData";
uigoodssearch.onCmd = "uigoodssearchCmd";
uigoodssearch.onSelect = "uigoodssearchSelect";
uigoodssearch.onSelectM = "";
uigoodssearch.show("idgoodssearch");

function uigoodssearchGetData(idinput, mode) {
    //neu nhan chon lua
    var search_key = uriEncode(getValById(idinput));
    if (mode == 0)
        search_key = "goods_name=" + uriEncode(search_key);
    else
        search_key = "goods_code=" + uriEncode(search_key);
    var url = "?page=list&pagesub=goods&invoice_type=" + g_pageobj['{_UID_}'].m_invoice_type + "&" + search_key + "&contact_id=" + g_pageobj['{_UID_}'].m_contact_id + "&store_id=" + getSelectVal("select_store_id");

    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            data = getDataOk(data);
            var rows = data.split(g_split_row);
            var dataset = [];
            for (i = 0; i < rows.length; i++) {
                if (rows[i].substr(0, g_sign_columnconfig.length) == g_sign_columnconfig)
                    continue;
                if (rows[i].substr(0, g_sign_pageconfig.length) == g_sign_pageconfig)
                    continue;
                dataset[dataset.length] = rows[i];
            }

            uigoodssearch.showList(dataset);
            showWaitStatus();
        },
        error: function () {
            showMsg(itxt("loi"));
            showWaitStatus();
        }
    });
}

function uigoodssearchCmd() {
    DlgSelect.showGoods(1, 'uigoodssearchCmd_Done', null, null, 1, getValById("select_store_id"), null, null, g_pageobj['{_UID_}'].m_invoice_type);
}
function uigoodssearchCmd_Done(id, goods_id, unit_id, tenhang, mahang, dvt, ton, dongia, mausac, mausacid, kichthuoc, anh, template_id) {
    if (isEmpty(dvt)) dvt = "";
    g_pageobj['{_UID_}'].invoiceGoodsAdd(goods_id, parseNumberVn(unit_id), 1, tenhang, dvt, parseNumberVn(dongia), mausac, template_id);
    setModalHeading("Đã thêm: " + tenhang);
}
function uigoodssearchSelect(vals) {

    //vals:id,goods_id,unit_id,tenhang,mahang,dvt,ton,dongia,mausac,mausacid,kichthuoc,anh,template_id
    if (vals.length < ds_goods_stock.length) return;
    //    invoiceGoodsAdd: function (goods_id, unit_id, quantity, goods_name, unit_name, export_price, color_name, template_id, parent_id, optional_extra_id, optional_quantity_max) {
    g_pageobj['{_UID_}'].invoiceGoodsAdd(vals[1], parseNumberVn(vals[2]), 1, vals[3], vals[5], parseNumberVn(vals[7]), vals[8], vals[12], null, parseNumberVn(vals[0]), parseNumberVn(vals[6]));
    setModalHeading("Đã thêm: " + vals[3]);
}
//end goodssearch box

//contactsearch box
function uicontactsearchGetData(idinput) {
    var search_key = uriEncode(getValById(idinput));
    var url = "?page=list&pagesub=contact_searchshort&contactname=" + search_key;
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (isDataFail(data)) {
                showMsg(getDataFail(data));
                return;
            }
            else if (isDataOk(data)) {
                data = getDataOk(data);
                var rows = data.split(g_split_row);
                var dataset = [];
                for (i = 0; i < rows.length; i++) {
                    if (rows[i].substr(0, g_sign_columnconfig.length) == g_sign_columnconfig)
                        continue;
                    if (rows[i].substr(0, g_sign_pageconfig.length) == g_sign_pageconfig)
                        continue;
                    dataset[dataset.length] = rows[i];
                }
                uicontactsearch.showList(dataset, false);
                showWaitStatus();
            }
            else
                showMsg(itxt("loi"));
            showWaitStatus();
        },
        error: function () {
            showMsg(itxt("loi"));
            showWaitStatus();
        }
    });
}
//id,name,address,phone...
function uicontactsearchSelect(vals) {
    if (vals.length < 4) {
        showMsg("dulieuloi");
        return;
    }
    g_pageobj['{_UID_}'].setContactId(vals[0]);
    var html = vals[1];
    if (vals[2] != "") {
        html += " (" + vals[2] + ")";
    }
    setValById(uicontactsearch.idinput, html);
    if (!isEmpty(uicontactsearch.fnOnChangeCB)) {
        eval(uicontactsearch.fnOnChangeCB)(vals);
    }
}
function uicontactsearchCmd() {
    DlgSelect.showContact(0, 'uicontactsearchCmd_Done');
}
function uicontactsearchCmd_Done(id, name, address, phone) {
    g_pageobj['{_UID_}'].setContactId(id);
    setValById(uicontactsearch.idinput, name);
    if (!isEmpty(uicontactsearch.fnOnChangeCB)) {
        eval(uicontactsearch.fnOnChangeCB)([id, name, address, phone]);
    }
}
var uicontactsearch = new UIListBoxEx("uicontactsearch", ds_contact_combo);
uicontactsearch.icon = "imgs/customers.png";
uicontactsearch.combobox_mode = true;
uicontactsearch.label_place_holder = "(khách lẻ)";
uicontactsearch.onGetData = "uicontactsearchGetData";
uicontactsearch.onCmd = "uicontactsearchCmd";
uicontactsearch.onSelect = "uicontactsearchSelect";
uicontactsearch.onSelectM = "";
uicontactsearch.show("idcontact");