function toggleStates(){
     $.ajax({
        url: "ajax/state.list.php",
        data: {
            id: $('#member_id').val(),
            country: $('#country').val()
        },
        type: "GET",
        success: function (result) {
            $('#state_row').html(result);
        }
    });
}

function toggleItemDeliveryMethodSelection() {
    let itemDeliveryMethodSelection = $('#itemDeliveryMethodSelection');

    let allDeliveryMethods = $('input[name="delivery_methods_all"]:checked').val();
    console.log(allDeliveryMethods);
    if (allDeliveryMethods === '1') {
        console.log('hide');
        itemDeliveryMethodSelection.hide();
    } else {
        console.log('show');
        itemDeliveryMethodSelection.show();
    }
}

$('document').ready(function (){
    'use strict';

    if ($('.printDespatchNote').length) {
        $('.printDespatchNote').on('click', function () {
            var id = $(this).attr('data-id');
            window.open(
                'order.printorder.php?id=' + id,
                'mywindow',
                'location=1, status=1, scrollbars=1, width=900, height=800');
        });
    }

    $("input.js_keywords_tagit").each(function (key, input) {
        $(input).tagit({
            allowSpaces: true,
            availableTags: window.all_keywords
        });
    });

    if ($('#orderStatusSelect').length) {
        $('#orderStatusSelect').change(function () {
            var selectEl = $(this),
                email_statuses = $.parseJSON(selectEl.attr('data-email_statuses'));

            if (email_statuses.indexOf(parseInt(selectEl.val())) == -1) {
                $('#sendStatusMailRow').css('visibility', 'hidden');
                $('#sendStatusMail').val(0);
            } else {
                $('#sendStatusMail').val(1);
                $('#sendStatusMailRow').css('visibility', 'visible');
            }
        });
    }
    
    if($('#country').length >0 && $('#state_row').length >0) {
        toggleStates();
        
        $('#country').on('change', function () {
            toggleStates();
        });
    }

    var productImportForm = $('#productImportForm');
    if (productImportForm.length > 0) {
        productImportForm.on('submit', function() {
            if ($('#add_products_import').is(':checked')) {
                if (!confirm('Are you sure you want new products to be created?')) {
                    return false;
                }
            }
        });
    }

    var bulkDeleteItemsToggle = $('.bulkDeleteItemsToggle');
    if (bulkDeleteItemsToggle.length) {
        bulkDeleteItemsToggle.on('change', function () {
            if ($(this).attr('checked')) {
                $('.bulkDeleteItems').attr('checked', true);
            } else {
                $('.bulkDeleteItems').attr('checked', false);
            }
        });
    }

    if ($('#editOrderItemForm').length) {

        $('#item_id').on('change', function() {
            load_sizes(true);
        });

        $('#sizeid').on('change', function () {
            $.get('/shop/admin/ajax.php', {
                action: 'get_size_data',
                item_id: $('#item_id').val(),
                size_id: $(this).val()
            }).success(function (response) {
                response = $.parseJSON(response);
                if (response.success) {
                    $('#item_price').val(response.data.display_price);
                    $('#item_price_exvat').val(response.data.display_price_exvat);
                    $('#price_paid').val(response.data.display_price);
                    $('#price_paid_exvat').val(response.data.display_price_exvat);
                    $('#PLU').val(response.data.PLU);
                    $('#vat_deductable').val(response.data.vat_deductable);
                } else if (response.error !== '') {
                    alert('Error: ' + response.error);
                }
            });
        });

        $('#private_prescription').on('change', function () {
            if ($(this).attr('checked')) {
                $('#PLU').val('private_prescription');
            } else {
                $('#PLU').val('');
            }
        });

        load_sizes(false);
    }


    //Workstation number confirmation
    $('#createShipmentBtn').on('click', function (e) {
        e.preventDefault();

        if(!$(this).hasClass('btnActive')) {
            $(this).addClass('btnActive');
        
            const $btn = $(this);
            const workstationNumber = prompt('Workstation number:');
    
            if (workstationNumber != null) {
                const url = `manage.order.php?action=create_shipment&id=${$btn.data('orderId')}&workstation_number=${workstationNumber}`
                window.location.assign(url);
            }
            
            setTimeout(function() {
                $btn.removeClass('btnActive');
            }, 500);

        }

    });

    let itemDeliveryMethodSelection = $('#itemDeliveryMethodSelection');

    if (itemDeliveryMethodSelection.length) {
        toggleItemDeliveryMethodSelection();

        $('input[name=delivery_methods_all]').change(function() {
            toggleItemDeliveryMethodSelection();
        });
    }
    
    
});

/**
 * If populate is true, triggers size change event which in turn populates order item data
 *
 * @param populate
 */
function load_sizes(populate) {
    if (!$('#item_id').length) {
        return;
    }
    var item_id = $('#item_id');
    if (item_id.val() === '' || item_id.val() === '0') {
        return;
    }
    $.get('/shop/admin/ajax.php', {
        action: 'get_item_sizes_options',
        item_id: item_id.val(),
        order_item_id: $('#order_item_id').val()
    }).success(function (response) {
        response = $.parseJSON(response);
        if (response.success) {
            $('#sizeid').html(response.html);
            $('#variationRow').removeClass('hideme');
            if (populate) {
                $('#sizeid').trigger('change');
            }
        } else if (response.error !== '') {
            alert('Error: ' + response.error);
        }
    });
}


