//Author: Faruk Bavčić
//Date: 25.12.2019
//Note: No specific module code allowed. Write only JS initializers!

$(document).ready(function () {
    moment.locale($("#languageDate").val());
    initializeDateTimePicker();
});

function initializeDateTimePicker() {
    $('.custom-datetimepicker').each(function (index, element) {
        dateTimePicker(element.id);
    });

    $('.custom-datepicker').each(function (index, element) {
        datePicker(element.id);
    });

    $('.custom-datepickerNoCurrent').each(function (index, element) {
        datePickerNoCurrent(element.id);
    });

    $(".custom-monthpicker").each(function (index, element) {
        monthPicker(element.id)
    });

    $(".custom-yearpicker").each(function (index, element) {
        yearPicker(element.id)
    });
}

function datePicker(elementId) {
    $('#' + elementId).datetimepicker({
        format: 'DD.MM.YYYY',
        locale: $('#languageDate').val()
    }).on('dp.change', function (event) {
        $(this).trigger('change');
    });
}

function datePickerNoCurrent(elementId) {
    $('#' + elementId).datetimepicker({
        format: 'DD.MM.YYYY',
        locale: $('#languageDate').val(),
        useCurrent: false
    }).on('dp.change', function (event) {
        $(this).trigger('change');
    });
}

function dateTimePicker(elementId) {
    $('#' + elementId).datetimepicker({
        format: 'DD.MM.YYYY HH:mm',
        locale: $('#languageDate').val()
    }).on('dp.change', function (event) {
        $(this).trigger('change');
    });
}

function monthPicker(elementId) {
    $('#' + elementId).datepicker({
        format: 'yyyy-mm',
        locale: $('#languageDate').val(),
        startView: "months",
        minViewMode: "months",
        maxViewMode: "years"
    }).on('dp.change', function (change) {
        $(this).trigger('change');
    });
}

function yearPicker(elementId) {
    $('#' + elementId).datepicker({
        format: 'yyyy',
        minViewMode: "years",
        maxViewMode: "years"
    }).on('dp.change', function (change) {
        $(this).trigger('change');
    });
}

function BuildSelectList(id, name, dataUrl, options, filterBy) {
    var select = new $('<select>')
        .attr('id', id)
        .attr('name', name)
        .attr('data-url', dataUrl)
        .attr('filter-by', filterBy)
        .attr('class', 'form-control select2WithUrl');

    $(options).each(function (index, element) {
        $(select).append(new Option(element.text, element.id));
    });

    return select;
}

function BuildDeleteButton(tableId, rowNumber) {
    let tabletMobileWidth = window.innerWidth <= 768;

    tableId = tableId.replace('#', '');

    var deleteIcon = new $('<span>')
        .attr('class', 'fa fa-times fa-lg text-danger');

    var deleteButton = new $('<button id="delete-record-' + tableId + '-' + rowNumber + '" type="button">')
        .attr('onclick', 'DeleteRow("' + tableId + '",' + rowNumber + ")")
        .attr('class', 'btn btn-outline')
        .html('<span class="far fa-trash-alt"></span>');

    if (tabletMobileWidth === true) {
        deleteButton.attr('class', 'btn btn-outline add-del-allow-expense');
    }

    return deleteButton;
}

function ajaxUploadDocument() {
    window.addEventListener("submit", function (e) {
        var form = e.target;
        if (form.getAttribute("enctype") === "multipart/form-data") {
            if (form.dataset.ajax) {
                e.preventDefault();
                e.stopImmediatePropagation();
                var xhr = new XMLHttpRequest();
                xhr.open(form.method, form.action);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        if (form.dataset.ajaxUpdate) {
                            var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                            if (updateTarget) {
                                updateTarget.innerHTML = xhr.responseText;
                            }
                        }
                    }
                };
                xhr.send(new FormData(form));
            }
        }
    }, true);
}

function uploadFile(inputId, base64Id, docNameId) {

    var fileList = document.getElementById(inputId).files;
    var fileReader = new FileReader();

    if (fileReader && fileList && fileList.length) {
        fileReader.readAsArrayBuffer(fileList[0]);
        fileReader.onload = function () {
            var imageData = fileReader.result;

            var stringData = btoa(String.fromCharCode.apply(null, new Uint8Array(imageData)));
            $('#' + base64Id).val(stringData);

            var fullPath = $('#' + inputId).val();

            var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
            var filename = fullPath.substring(startIndex);

            if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
                filename = filename.substring(1);
            }

            $('#' + docNameId).val(filename);
        };
    }
}

function openModal(id, worker = "") {
    $('#' + id).find('input[type="checkbox"]').customCheckbox();
    $('#' + id).modal('show');

    if (worker) {
        $("#AddParticipationForWorker").val(worker);
    } else if ($("#NewlyAddedWorker").val()) {
        $("#AddParticipationForWorker").val($("#NewlyAddedWorker").val());
    }
}

function initializeSwitcheryByElement(element) {
    new Switchery(element, { size: 'small' });
}