$(document).ready(function () {

    $('#save-material-btn').click(function () {
        saveNewMaterial();
    });

    $('#add-material-modal').on('shown.bs.modal', function () {
        loadNewPosition();
    });

    $('#add-material-modal').on('hidden.bs.modal', function () {
        clearSelections();
    });

    $('#selected-ident').change(function () {
        var selectedOption = $(this).find('option:selected');
        var measurementUnit = selectedOption.data('um');
        var description = selectedOption.data('name');
        $('#measurementUnit').val(measurementUnit);
        $('#description').val(description);
    });

    $('#b_dQuantity').click(function () {
        var quantity = $('#quantity');
        var currentValue = parseInt(quantity.val(), 10);

        if (currentValue > 0) {
            quantity.val(currentValue - 1);
        }
    });

    $('#b_iQuantity').click(function () {
        var quantity = $('#quantity');
        var currentValue = parseInt(quantity.val(), 10);
        quantity.val(currentValue + 1);
    });
});

function loadNewPosition() {
    $.ajax({
        type: 'GET',
        url: $('#GetNewMaterialPositionUrl').val(),
        data: {
            acKey: globalProcessingParams.acKey
        },
        success: function (response) {
            $('#position').val(response);
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function clearSelections() {
    $('#position, #measurementUnit, #description').val('');
    $('#quantity').val(0);
    $("#selected-ident").prop('selectedIndex', 0);
    $('.selectpicker').selectpicker('refresh');
}

function saveNewMaterial() {
    var formData = new FormData();
    formData.append('anNo', $('#position').val());
    formData.append('um', $('#measurementUnit').val());
    formData.append('Descr', $('#description').val());
    formData.append('ident', $('#selected-ident').val());
    formData.append('acKey', globalProcessingParams.acKey);
    formData.append('qty1', $('#quantity').val());
    formData.append('parentPlanQty', $('#parentPlanQuantity').val());

    $.ajax({
        cache: false,
        type: "POST",
        url: $('#AddNewMaterialUrl').val(),
        processData: false,
        contentType: false,
        data: formData,
        success: function () {
            $.fn.dataTable.reload($itemsTable);
            $('#add-material-modal').modal('hide');
        },
        error: function (error) {
            console.error(error);
        }
    });
}