var transferInventoryItem = {
    settings: {
        canApprove: '',
        ajaxUrl: '',
        ajaxUrlItemDelivery: '',
        formUrl: '',
        formActionUrl: '',
        doAddUrl: '',
        ajaxUrlDelivery: '',
        formUrlDelivery: '',
        formActionUrlDelivery: '',
        sendUrl: '',
        inventory_autocomplete_url: '',
        ajaxUrlItem: null,
        transferInventory_id: null,
        transferInventoryDeliveryDataList: null,
        transferInventoryItemDataList: null,
        branch_id: null,
        branchTo_id: null,
        transferInventoryItemDeliveryFormAll_url: '',
        transferInventoryItemDeliveryFormAllAction_url: '',
        transferInventoryItemDeliveryForm_url: '',
        transferInventoryItemDeliveryFormAction_url: '',
        itemIdQtys: ''
    },
    init: function() {
        transferInventoryItem.initDataTable();
        transferInventoryItem.bindHrefTransferInventoryItemSend();
        transferInventoryItem.bindHrefTransferInventoryItemForm();
        transferInventoryItem.bindHrefTransferInventoryDeliveryForm();
        transferInventoryItem.bindHrefTransferInventoryItemDeliveryFormAll();
        transferInventoryItem.bindRemoveSerialInput();
    },
    bindHrefTransferInventoryItemForm: function() {

        if(jQ('.href-transferInventoryItem-form').length > 0) {

            jQ('.href-transferInventoryItem-form').unbind('click').bind('click', function(){

                var requestName = 'transferInventoryItemForm',
                    modal = jQ('#modal'),
                    modalContent = jQ('#modal-content');

                global.ajaxCancel(requestName);

                var settings = {
                    url: transferInventoryItem.settings.formUrl,
                    type: 'GET',
                    data: {
                        transferInventory_id: transferInventoryItem.settings.transferInventory_id,
                        action: jQ(this).data('action'),
                        id: jQ(this).data('id')
                    },
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open');
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        modal.foundation('open');
                        global.bindFormSubmitted();
                        global.autocomplete.bind(transferInventoryItem.settings.inventory_autocomplete_url, '#transferInventoryItem_inventory_item_description', '#transferInventoryItem_inventory_id');
                        jQ('#transferInventoryItem_inventory_item_description').devbridgeAutocomplete('setOptions', {params: {status: 'Stock On Hand', branch_id: transferInventoryItem.settings.branch_id}});
                        transferInventoryItem.bindHrefTransferInventoryItemAction();
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindHrefTransferInventoryItemAction: function() {

        jQ('.href-transferInventoryItem-action').unbind('click.transferInventoryItemAction').bind('click.transferInventoryItemAction', function(){

            var requestName = 'transferInventoryItemAction',
                modal = jQ('#modal'),
                modalContent = jQ('#modal-content');

            global.formSubmitted();
            global.ajaxCancel(requestName);

            var settings = {
                url: transferInventoryItem.settings.formActionUrl,
                type: 'POST',
                data: jQ('#form-transferInventoryItem').serialize(),
                success: function(json) {
                    global.formSubmittedReverse();
                    if(json.success) {
                        transferInventoryItem.settings.transferInventoryItemDataList.draw();
                        global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'success', json.successMessages);
                        modal.foundation('close');
                    } else {
                        global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindHrefTransferInventoryItemSend: function() {

        /*if(jQ('#href-transferInventory-send').length > 0) {

            jQ('#href-transferInventory-send').unbind('click').bind('click', function(){

                if(confirm('Are you sure you want to send this transaction?')) {

                    var requestName = 'transferInventorySend',
                        modal = jQ('#modal'),
                        modalContent = jQ('#modal-content');

                    global.ajaxCancel(requestName);

                    var settings = {
                        url: transferInventoryItem.settings.sendUrl,
                        type: 'POST',
                        data: {
                            transferInventory_id: transferInventoryItem.settings.transferInventory_id
                        },
                        beforeSend: function() {
                            modalContent.html('').addClass('has-loading');
                            modal.foundation('open');
                        },
                        success: function(json) {
                            if(json.success) {
                                location.reload();
                            } else {
                                global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'alert', json.errorMessages);
                                modal.foundation('close');
                            }
                        }
                    };

                    global.ajax(settings, requestName);
                }
            });
        }*/

        jQ('#btn-send-ask-modal-continue').unbind('click').bind('click', function(){

            var requestName = 'transferInventorySend',
                modal = jQ('#modal'),
                modalContent = jQ('#modal-content'),
                _form = jQ('#form-transferInvItem');
            global.ajaxCancel(requestName);

            var settings = {
                url: transferInventoryItem.settings.sendUrl,
                type: 'POST',
                data: {
                    form: _form.serializeArray(),
                    transferInventory_id: transferInventoryItem.settings.transferInventory_id
                },
                beforeSend: function() {
                    modalContent.html('').addClass('has-loading');
                    modal.foundation('open');
                },
                success: function(json) {
                    if(json.success) {
                        location.reload();
                    } else {
                        global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'alert', json.errorMessages);
                        modal.foundation('close');
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindHrefTransferInventoryDeliveryForm: function() {

        if(jQ('.href-transferInventoryDelivery-form').length > 0) {

            jQ('.href-transferInventoryDelivery-form').unbind('click').bind('click', function(){

                var requestName = 'transferInventoryDeliveryForm',
                    modal = jQ('#modal'),
                    modalContent = jQ('#modal-content');

                global.ajaxCancel(requestName);

                var settings = {
                    url: transferInventoryItem.settings.formUrlDelivery,
                    type: 'GET',
                    data: {
                        transferInventory_id: transferInventoryItem.settings.transferInventory_id,
                        action: jQ(this).data('action'),
                        id: jQ(this).data('id')
                    },
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open');
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        modal.foundation('open');
                        global.bindFormSubmitted();
                        global.draggableReveal();
                        global.maskInput();
                        jQ('#transferInventoryItem-datalist-forDelivery').DataTable({
                            paging: false,
                            ordering: false,
                            searching: false,
                            info: false
                        });
                        transferInventoryItem.bindHrefTransferInventoryDeliveryAction();
                        jQ('.delivery_add_serial_input_btn').unbind('click').bind('click', transferInventoryItem.delivery_doAddSerialInputBtn);
                        transferInventoryItem.delivery_bindRemoveSerialInput();
                        jQ('#transferInventoryItem-datalist-forDeliveryz .delivery_inventory_serial_no_select').each(function (i, el) {
                           jQ(el).select2();
                           jQ(el).on('select2:select', function (e) {
                               if(e.params.data.id !== '') {
                                   let add_flag = true;
                                   jQ('.delivery_inventory_serial_no_select').each(function (i, el) {
                                       if (jQ(el).val() === '') {
                                           jQ(el).select2('open');
                                           add_flag = false;
                                       }
                                   });
                                   if(add_flag) {
                                       jQ('.delivery_add_serial_input_btn').click();
                                   }
                               }
                               transferInventoryItem.delivery_computeQty(jQ(el).data('btn_add_el'));
                           });
                        });
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindHrefTransferInventoryDeliveryAction: function() {

        jQ('.href-transferInventoryDelivery-action').unbind('click.transferInventoryDeliveryAction').bind('click.transferInventoryDeliveryAction', function(){

            var requestName = 'transferInventoryDeliveryAction',
                modal = jQ('#modal'),
                modalContent = jQ('#modal-content');

            global.formSubmitted();
            global.ajaxCancel(requestName);

            var settings = {
                url: transferInventoryItem.settings.formActionUrlDelivery,
                type: 'POST',
                data: jQ('#form-transferInventoryDelivery').serialize(),
                success: function(json) {
                    if(json.success) {
                        //transferInventoryItem.settings.transferInventoryDeliveryDataList.draw();
                        //transferInventoryItem.settings.transferInventoryItemDataList.draw();
                        global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'success', json.successMessages);
                        // modal.foundation('close');
                        location.reload();
                    } else {
                        global.formSubmittedReverse();
                        global.flashMessage('alert', json.errorMessages);
                        //global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindHrefTransferInventoryItemDeliveryFormAll: function() {

        if(jQ('#href-transferInventoryItemDelivery-formAll').length > 0) {

            jQ('#href-transferInventoryItemDelivery-formAll').unbind('click').bind('click', function(){

                var requestName = 'transferInventoryItemDeliveryFormAll',
                    modal = jQ('#modal'),
                    modalContent = jQ('#modal-content');

                global.ajaxCancel(requestName);

                var settings = {
                    url: transferInventoryItem.settings.transferInventoryItemDeliveryFormAll_url,
                    type: 'GET',
                    data: {
                        transferInventory_id: transferInventoryItem.settings.transferInventory_id
                    },
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open');
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        global.bindFormSubmitted();
                        transferInventoryItem.bindHrefTransferInventoryItemDeliveryActionAll();
                        jQ('#transferInventoryItemList-datalist').DataTable({
                            'searching': false,
                            'paging': false,
                            'columnDefs': [
                                {'orderable': false, 'targets': [0, 1, 2, 3]}
                            ]
                        });
                        global.maskInput();
                        modal.foundation('open');
                        jQ('.receive_add_serial_input_btn').unbind('click').bind('click', transferInventoryItem.receive_doAddSerialInputBtn);
                        transferInventoryItem.receive_bindRemoveSerialInput();
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindHrefTransferInventoryItemDeliveryActionAll: function() {

        jQ('#href-transferInventoryItemDelivery-actionAll').unbind('click.transferInventoryItemDeliveryActionAll').bind('click.transferInventoryItemDeliveryActionAll', function(){

            var requestName = 'transferInventoryItemDeliveryActionAll';

            global.formSubmitted();
            global.ajaxCancel(requestName);

            var settings = {
                url: transferInventoryItem.settings.transferInventoryItemDeliveryFormAllAction_url,
                type: 'POST',
                data: jQ('#form-transferInventoryItemDelivery').serialize(),
                success: function(json) {
                    if(json.success) {
                        location.reload();
                    } else {
                        global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                        global.formSubmittedReverse();
                    }
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindHrefTransferInventoryItemDeliveryForm: function() {

        if(jQ('.href-transferInventoryItemDelivery-form').length > 0) {

            jQ('.href-transferInventoryItemDelivery-form').unbind('click').bind('click', function(){

                var requestName = 'transferInventoryFormItemDelivery',
                    modal = jQ('#modal'),
                    modalContent = jQ('#modal-content');

                global.ajaxCancel(requestName);

                var settings = {
                    url: transferInventoryItem.settings.transferInventoryItemDeliveryForm_url,
                    type: 'GET',
                    data: {
                        transferInventoryItem_id: jQ(this).data('ref-id'),
                        action: jQ(this).data('action'),
                        id: jQ(this).data('id')
                    },
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open');
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        global.bindFormSubmitted();
                        modal.foundation('open');
                        transferInventoryItem.bindHrefTransferInventoryItemDeliveryAction();
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindHrefTransferInventoryItemDeliveryAction: function() {

        jQ('.href-transferInventoryItemDelivery-action').unbind('click.transferInventoryItemDeliveryAction').bind('click.transferInventoryItemDeliveryAction', function(){

            var requestName = 'transferInventoryItemDeliveryAction';

            global.formSubmitted();
            global.ajaxCancel(requestName);

            var settings = {
                url: transferInventoryItem.settings.transferInventoryItemDeliveryFormAction_url,
                type: 'POST',
                data: jQ('#form-transferInventoryItemDelivery').serialize(),
                success: function(json) {
                    if(json.success) {
                        location.reload();
                    } else {
                        global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                        global.formSubmittedReverse();
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    doAddItem: function() {
        var _self = jQ(this),
            settings = {
                url: transferInventoryItem.settings.doAddUrl,
                type: 'POST',
                data: {
                    transferInventory_id:  transferInventoryItem.settings.transferInventory_id,
                    id: jQ(this).data('id'),
                    quantity:  jQ('#addItemForm-qty-'+ jQ(this).data('key')).val(),
                    note:  jQ('#addItemForm-note-'+ jQ(this).data('key')).val(),
                    consumable:  jQ('#addItemForm-consumable-'+ jQ(this).data('key')).is(":checked"),
                    serialNos:  jQ(`.addItemForm-serialNos-${jQ(this).data('key')}`).map(function() {
                        return this.value;
                    }).get(),
                },
                beforeSend: function() {
                    _self.parent().addClass('autocomplete-loading');
                },
                error: function() {
                    alert('Something went wrong. Please try again or contact the administrator.');
                    _self.parent().removeClass('autocomplete-loading');
                },
                success: function(result) {
                    if(!result.success){
                        alert(result.messages);
                        _self.parent().removeClass('autocomplete-loading');
                    } else {
                        transferInventoryItem.settings.transferInventoryItemDataList.draw();
                        _self.parent().removeClass('autocomplete-loading');
                    }
                }
            };
        global.ajax(settings, 'Do Add Item');
    },
    doRemoveItem: function() {
        var _self = jQ(this),
            settings = {
                url: transferInventoryItem.settings.doRemoveUrl,
                type: 'POST',
                data: {
                    id: jQ(this).data('id')
                },
                beforeSend: function() {
                    _self.parent().addClass('autocomplete-loading');
                },
                error: function() {
                    alert('Something went wrong. Please try again or contact the administrator.');
                    _self.parent().removeClass('autocomplete-loading');
                },
                success: function() {
                    transferInventoryItem.settings.transferInventoryItemDataList.draw();
                    _self.parent().removeClass('autocomplete-loading');
                }
            };
        global.ajax(settings, 'Do Remove Item');
    },
    initDataTable: function() {

        var callBack = function() {
            // transferInventoryItem.bindHrefTransferInventoryItemForm();
            jQ('.href-transferInventoryItem-remove').unbind('click').bind('click', transferInventoryItem.doRemoveItem);
        };

        transferInventoryItem.settings.transferInventoryItemDataList = jQ('#transferInventoryItem-datalist').DataTable({
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': transferInventoryItem.settings.ajaxUrl,
                'data': function(d) {
                    d.transferInventory_id = transferInventoryItem.settings.transferInventory_id;
                }
            },
            'columnDefs': [
                { 'orderable': false, 'targets': jQ('#transferInventoryItem-datalist th').length - 1 },
                { 'searchable': false, 'targets':  jQ('#transferInventoryItem-datalist th').length - 1 }
            ],
            drawCallback: callBack,
            responsive: {
                details: {
                    renderer: function(api, rowIdx) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBack);
                    }
                }
            },
            createdRow: function(tr, data) {
                const jqTr = jQ(tr);
                jQ(jqTr.children()[1]).addClass('text-right');
                jQ(jqTr.children()[5]).addClass('text-right');
                jQ(jqTr.children()[3]).addClass('text-right');
                jQ(jqTr.children()[4]).addClass('text-right');
                jQ(jqTr.children()[jQ('#transferInventoryItem-datalist th').length - 1]).addClass('text-center');
            }
        });

        jQ('#materialRequisition-datalist').DataTable({
            paging: false,
            ordering: false,
            searching: false,
            info: false
        });

        jQ('#transferInventoryStatusHistory-datalist').DataTable({
            paging: false,
            ordering: false,
            searching: false,
            info: false
        });

        if(jQ('#transferInventoryDelivery-datalist').length) {

            const callBackDelivery = function() {
                transferInventoryItem.bindHrefTransferInventoryDeliveryForm();
            };

            transferInventoryItem.settings.transferInventoryDeliveryDataList = jQ('#transferInventoryDelivery-datalist').DataTable({
                'processing': true,
                'serverSide': true,
                'ajax': {
                    'url': transferInventoryItem.settings.ajaxUrlDelivery,
                    'data': function(d) {
                        d.transferInventory_id = transferInventoryItem.settings.transferInventory_id;
                    }
                },
                'columnDefs': [
                    { 'orderable': false, 'targets': [1, 2, 3] },
                    { 'searchable': false, 'targets': [1, 2, 3] }
                ],
                order: [[1, 'desc']],
                drawCallback: callBackDelivery,
                responsive: {
                    details: {
                        renderer: function(api, rowIdx) {
                            return global.dataTableResponsiveCallBack(api, rowIdx, callBackDelivery);
                        }
                    }
                },
                createdRow: function(tr) {
                    //jQ(jQ(tr).children()[1]).addClass('text-right');
                }
            });
        }

        if(jQ('#transferInventoryItemDelivery-datalist').length > 0) {

            var callBackItemDelivery = function() {
                transferInventoryItem.bindHrefTransferInventoryItemDeliveryForm();
            };

            transferInventoryItem.settings.transferInventoryItemDeliveryDataList = jQ('#transferInventoryItemDelivery-datalist').DataTable({

                'processing': true,
                'serverSide': true,
                'ajax': {
                    'url': transferInventoryItem.settings.ajaxUrlItemDelivery,
                    'data': function(d) {
                        d.transferInventory_id = transferInventoryItem.settings.transferInventory_id;
                    }
                },
                'columnDefs': [
                    { 'orderable': false, 'targets': 3 },
                    { 'searchable': false, 'targets': 3 }
                ],
                drawCallback: callBackItemDelivery,
                responsive: {
                    details: {
                        renderer: function( api,rowIdx ) {
                            return global.dataTableResponsiveCallBack(api, rowIdx, callBackItemDelivery);
                        }
                    }
                },
                createdRow: function(tr) {
                    jQ(jQ(tr).children()[2]).addClass('text-right');
                }
            });
        }

        const callBackItem = function() {
            jQ('.href-item-add').unbind('click').bind('click', transferInventoryItem.doAddItem);
            jQ('.add_serial_input_btn').unbind('click').bind('click', transferInventoryItem.doAddSerialInputBtn);
            global.maskInput();
            if(jQ('#modal-add-item').is(':visible')){
                jQ('#modal-add-item').foundation('close');
                jQ('#modal-add-item').foundation('open');
            }
            jQ('.select2').select2();
        };

        const datalistItem = jQ('#item-datalist').DataTable({
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': transferInventoryItem.settings.ajaxUrlItem,
                'data': function(d) {
                    d.branchId = transferInventoryItem.settings.branch_id;
                    d.itemCategory_id = jQ('#addItemFormFilter-itemCategory').val();
                    d.itemIdQtys = JSON.parse(transferInventoryItem.settings.itemIdQtys);
                }
            },
            'columnDefs': [
                { 'orderable': false, 'targets': [1,2,3,4] },
                { 'searchable': false, 'targets': [1,2,3,4] }
            ],
            //ordering: false,
            drawCallback: callBackItem,
            responsive: {
                details: {
                    renderer: function( api,rowIdx ) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBackItem);
                    }
                }
            }
        });

        jQ('#addItemFormFilter-itemCategory').unbind('change').bind('change', datalistItem.draw);

        jQ('.content-container').removeClass('has-loading'); jQ('.content-container-content').removeClass('hide');
    },
    
    doAddSerialInputBtn: function () {
        let is_itemised = jQ(this).data('is_itemised'),
            key = jQ(this).data('key'),
            serialNo_td = jQ(this).parent().parent().next(),
            div = jQ('<div>').css('display', 'flex'),
            _this = this;

        if(is_itemised == 1) {
            let serial_nos = jQ(this).data('serial_nos'),
                select = jQ('<select>').attr({
                    class: `input-small select2 inventory_serial_no_select addItemForm-serialNos-${key}`,
                }).html('<option></option>'),
                remove_btn = `<button type="button" data-key="${key}" class="action-button-style remove_serial_input_btn"><i class="fa fa-trash"></i></button>`;

            if(serial_nos === undefined) {
                serial_nos = "";
            }
            serial_nos = serial_nos.split(',');
            for (let i = 0; i < serial_nos.length; i++) {
                const serialNo = serial_nos[i].split('~');
                select.append(jQ('<option>').attr({value: serialNo[0]}).html(serialNo[1]));
            }
            div.append(select);
            div.append(remove_btn);
            serialNo_td.append(div);
            jQ('.select2').select2();
            jQ('#modal-add-item').foundation('close');
            jQ('#modal-add-item').foundation('open');
            select.select2('open');
            select.on('select2:select', function (e) {
                if(e.params.data.id !== '') {
                    let add_flag = true;
                    jQ('.inventory_serial_no_select').each(function (i, el) {
                        if (jQ(el).val() === '') {
                            jQ(el).select2('open');
                            add_flag = false;
                        }
                    });
                    if(add_flag) {
                        jQ('.add_serial_input_btn').click();
                    }
                }
                transferInventoryItem.computeQty(_this);
            });
            transferInventoryItem.computeQty(_this);
        }
    },
    bindRemoveSerialInput: function () {
        jQ('#modal-add-item').delegate('.remove_serial_input_btn', 'click', function () {
            let key = jQ(this).data('key');
            jQ(this).parent().remove();
            transferInventoryItem.computeQty(`#add_serial_input_btn-${key}`);
        });
    },
    computeQty: function (el) {
        let qty = 0;
        jQ(el).parent().parent().next().find('.inventory_serial_no_select').each(function (i, el) {
            if (jQ(el).val() !== '') {
                qty++;
            }
        });
        jQ(el).prev().val(qty);
    },


    delivery_doAddSerialInputBtn: function () {
        let is_itemised = jQ(this).data('is_itemised'),
            key = jQ(this).data('key'),
            serialNo_td = jQ(this).parent().parent().next(),
            div = jQ('<div>').css('display', 'flex'),
            _this = this;

        if(is_itemised == 1) {
            let serial_nos = jQ(this).data('serial_nos'),
                select = jQ('<select>').attr({
                    name: `otherForm[items][${key}][inventorySerialNo][]`,
                    class: `input-small select2 delivery_inventory_serial_no_select addItemForm-serialNos-${key}`,
                }).html('<option hidden></option>'),
                remove_btn = `<button type="button" data-key="${key}" class="action-button-style delivery_remove_serial_input_btn"><i class="fa fa-trash"></i></button>`;

            if(serial_nos === undefined) {
                serial_nos = "";
            }
            serial_nos = serial_nos.split(',');
            for (let i = 0; i < serial_nos.length; i++) {
                const serialNo = serial_nos[i].split('~');
                select.append(jQ('<option>').attr({value: serialNo[0]}).html(serialNo[1]));
            }
            div.append(select);
            div.append(remove_btn);
            serialNo_td.append(div);
            jQ('.select2').select2();
            jQ('#modal').foundation('close');
            jQ('#modal').foundation('open');
            select.select2('open');
            select.on('select2:select', function (e) {
                if(e.params.data.id !== '') {
                    let add_flag = true;
                    jQ('.delivery_inventory_serial_no_select').each(function (i, el) {
                        if (jQ(el).val() === '') {
                            jQ(el).select2('open');
                            add_flag = false;
                        }
                    });
                    if(add_flag) {
                        jQ('.delivery_add_serial_input_btn').click();
                    }
                }
                transferInventoryItem.delivery_computeQty(_this);
            });
            transferInventoryItem.delivery_computeQty(_this);
        }
    },
    delivery_bindRemoveSerialInput: function () {
        jQ('#modal').delegate('.delivery_remove_serial_input_btn', 'click', function () {
            let key = jQ(this).data('key');
            jQ(this).parent().remove();
            transferInventoryItem.delivery_computeQty(`#delivery_add_serial_input_btn-${key}`);
        });
    },
    delivery_computeQty: function (el) {
        let qty = 0;
        jQ(el).parent().parent().next().find('.delivery_inventory_serial_no_select').each(function (i, el) {
            if (jQ(el).val() !== '') {
            qty++;
            }
        });
        jQ(el).prev().val(qty);
    },


    receive_doAddSerialInputBtn: function () {
        let is_itemised = jQ(this).data('is_itemised'),
            key = jQ(this).data('key'),
            serialNo_td = jQ(this).parent().parent().next(),
            div = jQ('<div>').css('display', 'flex'),
            _this = this;

        if(is_itemised == 1) {
            let serial_nos = jQ(this).data('serial_nos'),
                select = jQ('<select>').attr({
                    name: `transferInventoryItems[${key}][inventorySerialNo][]`,
                    class: `input-small select2 receive_inventory_serial_no_select addItemForm-serialNos-${key}`,
                }).html('<option hidden></option>'),
                remove_btn = `<button type="button" data-key="${key}" class="action-button-style receive_remove_serial_input_btn"><i class="fa fa-trash"></i></button>`;

            if(serial_nos === undefined) {
                serial_nos = "";
            }
            serial_nos = serial_nos.split(',');
            for (let i = 0; i < serial_nos.length; i++) {
                const serialNo = serial_nos[i].split('~');
                select.append(jQ('<option>').attr({value: serialNo[0]}).html(serialNo[1]));
            }
            div.append(select);
            div.append(remove_btn);
            serialNo_td.append(div);
            jQ('.select2').select2();
            jQ('#modal').foundation('close');
            jQ('#modal').foundation('open');
            select.select2('open');
            select.on('select2:select', function (e) {
                if(e.params.data.id !== '') {
                    let add_flag = true;
                    jQ('.receive_inventory_serial_no_select').each(function (i, el) {
                        if (jQ(el).val() === '') {
                            jQ(el).select2('open');
                            add_flag = false;
                        }
                    });
                    if(add_flag) {
                        jQ('.receive_add_serial_input_btn').click();
                    }
                }
                transferInventoryItem.receive_computeQty(_this);
            });
            transferInventoryItem.receive_computeQty(_this);
        }
    },
    receive_bindRemoveSerialInput: function () {
        jQ('#modal').delegate('.receive_remove_serial_input_btn', 'click', function () {
            let key = jQ(this).data('key');
            jQ(this).parent().remove();
            transferInventoryItem.receive_computeQty(`#receive_add_serial_input_btn-${key}`);
        });
    },
    receive_computeQty: function (el) {
        let qty = 0;
        jQ(el).parent().parent().next().find('.receive_inventory_serial_no_select').each(function (i, el) {
            if (jQ(el).val() !== '') {
            qty++;
            }
        });
        jQ(el).prev().val(qty);
    },
};