var canvass_view = {
    settings: {
        canvass_id: null,
        ajaxUrl: '',
        sendUrl: '',
        addQuantityUrl: '',
        voidUrl: '',
        voidActionUrl: '',
        cancelUrl: '',
        canvassItemSupplierForm_url: '',
        canvassItemSupplierFormAction_url: '',
        canvassItemSupplierSelect_url: '',
        canvassItemSupplierSelectAction_url: '',
        canvassItemSupplierDetails_url: '',
        canvassItemSupplierRemove_url: '',
        supplier_autocomplete_url: '',
        canvassItemDataList: null,
        addQuantityActionUrl:'',
        item_category_autocomplete_url:''
    },
    init: function() {
        canvass_view.initDataTable();
        canvass_view.bindHrefCanvassItemSupplierSend();
        canvass_view.bindHrefCanvassVoid();
        canvass_view.bindHrefCanvassCancel();
        canvass_view.bindHrefCanvassAddQuantity();
        canvass_view.bindAutocomplete();
    },
    bindHrefCanvassItemSupplierForm: function() {

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

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

                /*jQ('#addSupplierForm-canvassItem-id').val(jQ(this).data('ref-id'));
                jQ('#modal-title-add-supplier-form').html('Add Supplier for Item: ' + jQ(this).data('item-desc'));
                jQ('#modal-add-supplier-form').foundation('open');*/

                var canvassItem_id = jQ(this).data('ref-id'),
                    requestName = 'canvassItemSupplierForm',
                    modal = jQ('#modal'),
                    modalContent = jQ('#modal-content');

                global.ajaxCancel(requestName);

                var settings = {
                    url: canvass_view.settings.canvassItemSupplierFormMultiple_url,
                    type: 'GET',
                    data: {
                        canvassItem_id: canvassItem_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.draggableReveal();
                        modal.foundation('open');
                        modal.css('top', (jQ(window).scrollTop() + 50) + 'px').css('margin-top', '0');

                        const addSuppCallback = function() {
                            jQ('.href-addSupplierForm-doAdd').unbind('click').bind('click', canvass_view.doAddSupplier);
                        };

                        jQ('#addSupplierForm-datalist').DataTable({
                            'processing': true,
                            'serverSide': true,
                            'ajax': {
                                'url': canvass_view.settings.supplier_ajaxUrl,
                                data: {
                                    item_id: jQ('#addSupplierForm-item-id').val(),
                                    canvass_id: canvass_view.settings.canvass_id
                                }
                            },
                            'columnDefs': [
                                { 'orderable': false, 'targets': [2, 3, 4, 5, 6, 7, 8] },
                                { 'searchable': false, 'targets': [2, 3, 4, 5, 6, 7, 8] }
                            ],
                            orderClasses: false,
                            drawCallback: addSuppCallback,
                            responsive: {
                                details: {
                                    renderer: function(api, rowIdx) {
                                        return global.dataTableResponsiveCallBack(api, rowIdx, addSuppCallback);
                                    }
                                }
                            }
                        });

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

                        global.bindFormSubmitted();

                        // global.autocomplete.bind(canvass_view.settings.supplier_autocomplete_url, '#canvassItemSupplier_supplier_description', '#canvassItemSupplier_supplier_id');
                        // canvass_view.bindHrefCanvassItemSupplierAction();
                    }
                };

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

        }
    },
    bindHrefCanvassItemSupplierAction: function() {

        jQ('.href-canvassItemSupplier-action').unbind('click.canvassItemSupplierAction').bind('click.canvassItemSupplierAction', function(){

            var requestName = 'canvassItemSupplierAction',
                modal = jQ('#modal');

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

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

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

        if(jQ('.href-canvassItemSupplier-select').length > 0) {

            jQ('.href-canvassItemSupplier-select').unbind('click').bind('click', function(){
                canvass_view.doHrefCanvassItemSupplierSelect(jQ(this).data('ref-id'));
            });
        }
    },
    doHrefCanvassItemSupplierSelect: function(canvassItem_id) {

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

        global.ajaxCancel(requestName);

        var settings = {
            url: canvass_view.settings.canvassItemSupplierSelect_url,
            type: 'GET',
            data: {
                canvassItem_id: canvassItem_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.draggableReveal();
                modal.foundation('open');
                global.bindFormSubmitted();
                jQ('#canvassItemSupplier-datalist-select').DataTable({
                    'paging': false,
                    'searching': false,
                    'ordering': false,
                    'info': false
                });
                jQ('#supplierFormSelect-history-datalist').DataTable({
                    'paging': false,
                    'searching': false,
                    'info': false,
                    'ordering': false
                });
                canvass_view.bindHrefCanvassItemSupplierSelectAction();
                canvass_view.bindHrefCanvassItemSupplierRemove();
            }
        };

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

        jQ('.href-canvassItemSupplierSelect-action').unbind('click.canvassItemSupplierSelectAction').bind('click.canvassItemSupplierSelectAction', function(){

            var requestName = 'canvassItemSupplierSelectAction',
                modal = jQ('#modal-large');

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

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

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

        jQ('.href-canvassItemSupplier-remove').unbind('click.canvassItemSupplierRemove').bind('click.canvassItemSupplierRemove', function(){

            if(confirm('Are you sure you want to remove this record?')) {

                var canvassItem_id = jQ(this).data('ref-id'),
                    canvassItemSupplier_id = jQ(this).data('id'),
                    requestName = 'canvassItemSupplierRemove';

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

                var settings = {
                    url: canvass_view.settings.canvassItemSupplierRemove_url,
                    type: 'POST',
                    data: {
                        canvassItemSupplier_id: canvassItemSupplier_id
                    },
                    success: function(json) {
                        if(json.success) {
                            canvass_view.settings.canvassItemDataList.draw();
                            canvass_view.doHrefCanvassItemSupplierSelect(canvassItem_id);
                            global.formSubmittedReverse();
                        } else {
                            global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'alert', json.errorMessages);
                            global.formSubmittedReverse();
                        }
                    }
                };

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

        if(jQ('.href-canvassItemSupplier-details').length > 0) {

            jQ('.href-canvassItemSupplier-details').unbind('click').bind('click', function(){

                var canvassItem_id = jQ(this).data('ref-id'),
                    requestName = 'canvassItemSupplierDetails',
                    modal = jQ('#modal'),
                    modalContent = jQ('#modal-content');

                global.ajaxCancel(requestName);

                var settings = {
                    url: canvass_view.settings.canvassItemSupplierDetails_url,
                    type: 'GET',
                    data: {
                        canvassItem_id: canvassItem_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.draggableReveal();
                        modal.foundation('open');
                        jQ('#canvassItemSupplier-datalist').DataTable({'paging': false, 'searching': false});
                    }
                };

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

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

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

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

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

                    global.ajaxCancel(requestName);

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

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

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

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

            global.ajaxCancel(requestName);

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

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

        if(jQ('#href-canvass-void').length > 0) {

            jQ('#href-canvass-void').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: canvass_view.settings.voidUrl,
                    type: 'GET',
                    data: {
                        canvass_id: canvass_view.settings.canvass_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.draggableReveal();
                        global.bindFormSubmitted();
                        canvass_view.bindHrefCanvassVoidAction();
                        jQ('#canvassItemVoid-datalist').DataTable({
                            'searching': false,
                            'paging': false,
                            'columnDefs': [
                                {'orderable': false, 'targets': [0, 1, 2, 3]}
                            ]
                        });
                        modal.foundation('open');
                    }
                };

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

        jQ('#href-canvassVoid-action').unbind('click.canvassVoidAction').bind('click.canvassVoidAction', function(){

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

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

            var settings = {
                url: canvass_view.settings.voidActionUrl,
                type: 'POST',
                data: jQ('#form-canvassVoid').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);
        });
    },
    bindHrefCanvassCancel: function() {

        if(jQ('#href-canvass-cancel').length > 0) {

            jQ('#href-canvass-cancel').unbind('click').bind('click', function(){

                if(confirm('Are you sure you want to cancel this request?')) {

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

                    global.ajaxCancel(requestName);

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

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

        var callBack = function() {
            canvass_view.bindHrefCanvassItemSupplierForm();
            canvass_view.bindHrefCanvassItemSupplierSelect();
            canvass_view.bindHrefCanvassItemSupplierDetails();
        };

        canvass_view.settings.canvassItemDataList = jQ('#canvassItem-datalist').DataTable({
            'pageLength': 200,
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': canvass_view.settings.ajaxUrl,
                'data': function(d) {
                    d.canvass_id = canvass_view.settings.canvass_id;
                    d.item_category_id = jQ('#item_category_id').val();
                }
            },
            'columnDefs': [
                { 'orderable': false, 'targets': 4 },
                { 'searchable': false, 'targets': 4 }
            ],
            drawCallback: function() {
                callBack();
            },
            responsive: {
                details: {
                    renderer: function( api,rowIdx ) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBack);
                    }
                }
            }
        });

        jQ('#canvassStatusHistory-datalist').DataTable({
            'order': [[0, 'desc']]
        });

        jQ('#purchaseOrder-datalist').DataTable();

        jQ('#purchaseOrderStatusHistory-datalist').DataTable({
            'order': [[1, 'desc']]
        });

        jQ('.content-container').removeClass('has-loading'); jQ('.content-container-content').removeClass('hide');
    },

    bindHrefCanvassAddQuantity: function() {

        if(jQ('#href-canvass-add-quantity').length > 0) {

            jQ('#href-canvass-add-quantity').unbind('click').bind('click', function(){

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: canvass_view.settings.addQuantityUrl,
                    type: 'GET',
                    data: {
                        canvass_id: canvass_view.settings.canvass_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.draggableReveal();
                        global.bindFormSubmitted();
                        canvass_view.bindHrefCanvassAddQuantityAction();
                        jQ('#canvassItemAddQuantity-datalist').DataTable({
                            'searching': false,
                            'paging': false,
                            'columnDefs': [
                                {'orderable': false, 'targets': [0, 1, 2, 3]}
                            ]
                        });
                        modal.foundation('open');
                    }
                };

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

    bindHrefCanvassAddQuantityAction: function() {

        jQ('#href-canvassAddQuantity-action').unbind('click.canvassAddQuantityAction').bind('click.canvassAddQuantityAction', function(){

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

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

            var settings = {
                url: canvass_view.settings.addQuantityActionUrl,
                type: 'POST',
                data: jQ('#form-canvassAddQuantity').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);
        });
    },

    bindAutocomplete: function() {
        global.autocomplete.bind(
            canvass_view.settings.item_category_autocomplete_url,
            '#item_category_description',
            '#item_category_id',
            {
                onSelect : function(){
                    canvass_view.settings.canvassItemDataList.draw();
                }
            }
        );
    },

    doAddSupplier: function() {
        var _self = jQ(this),
            id = _self.data('id'),
            settings = {
                url: canvass_view.settings.canvassItemSupplierDoAdd_url,
                type: 'POST',
                data: {
                    canvass_id:  canvass_view.settings.canvass_id,
                    canvassItem_id: jQ('#addSupplierForm-canvassItem-id').val(),
                    supplier_id: id,
                    currency_id: jQ('#addSupplierForm-currency-' + id).val(),
                    paymentMode: jQ('#addSupplierForm-paymentMode-' + id).val(),
                    term: jQ('#addSupplierForm-term-' + id).val(),
                    wTaxRate_id: jQ('#addSupplierForm-wTaxRate-' + id).val(),
                    price: jQ('#addSupplierForm-price-' + id).val(),
                    // qty: jQ('#addSupplierForm-qty-' + id).val(),
                    note: jQ('#addSupplierForm-note-' + id).val()
                },
                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.errorMessages);
                        _self.parent().removeClass('autocomplete-loading');
                    } else {
                        canvass_view.settings.canvassItemDataList.draw();
                        _self.parent().removeClass('autocomplete-loading');
                    }
                }
            };
        global.ajax(settings, 'Do Add Supplier');
    }
};