function initializeCompanyCompany() {
    dropifyUpload();

    $(".datepicker").datepicker({
        format: 'dd.mm.yyyy',
        language: $('#siteLocale').val()
    }).on('changeDate', function () {
        $(this).datepicker('hide');
    });

    initializePartnerTypeahead($('#Company').attr('dataUrl'), $('#Company'), $("#CompanyId"), function (item) {
        $("#IsCompanyVat").val(item.isVAT);
    });

    $('#Company').on("blur", function () {
        if ($('#Company').val() !== $("#CompanyId").val()) {
            $('#Company').val($("#CompanyId").val());
        }
    });

    $('#IsCompanyVatSwitch').on("change", function () {
        $("#IsCompanyVat").val($(this).is(':checked'));
        $("#IsCompanyVatDisplaySwitch").val($(this).is(':checked'));
        $('#IsCompanyVatDisplaySwitch').removeAttr("disabled");
        $('#IsCompanyVatDisplaySwitch').trigger('click');
    });

    var elems = Array.prototype.slice.call(document.querySelectorAll('.company-js-switch'));
    elems.forEach(function (html) {
        var switchery = new Switchery(html, { size: 'small' });
    });

    $('.edit-form-button').on('click', function () {
        var form = $(this).closest('form');

        form.find('.form-display-element').css('display', 'none');
        form.find('.form-edit-element').css('display', 'block');
    });

    $('.cancel-button').on('click', function () {
        var form = $(this).closest('form');

        var displayElements = form.find('.form-display-element');
        $.each(displayElements, function () {
            var editElement = $(this).closest('td').find('.form-edit-element');
            if (editElement) {
                if ($(this).closest('td').find('input').hasClass('js-switch-small')) {
                    var swtich = document.querySelector('#' + $(this).closest('td').find('input').attr('id'));
                    if (($(this).html() === $('#YesLoc').val() && !swtich.checked) || ($(this).html() === $('#NoLoc').val() && swtich.checked)) {
                        $('.js-switch-small').trigger('click');
                    }
                } else if ($(this).closest('td').find('input').attr('type') === 'file') {
                    $(this).closest('td').find('input').val("");
                } else {
                    $(this).closest('td').find('input').val($(this).html());
                }
            }
        });

        form.find('.form-display-element').css('display', 'block');
        form.find('.form-edit-element').css('display', 'none');
    });

    $('form').on('submit', function (e) {
        e.stopPropagation();
        e.preventDefault();

        var form = $(this);

        var submitIcon = form.find('button[type=submit] i');
        submitIcon.addClass('fa fa-spinner fa-spin');

        $.ajax({
            url: form.attr('action'),
            type: 'POST',
            data: new FormData(form[0]),
            cache: false,
            contentType: false,
            processData: false
        }).done(function (data) {
            if (data.Success === true) {
                var editElements = form.find('.form-edit-element');
                $.each(editElements, function () {
                    var displayElement = $(this).closest('td').find('.form-display-element');
                    if (displayElement) {
                        if ($(this).find('input').attr('type') === 'file') {
                            if ($(this).find('input').val() !== '') {
                                var file = $(this).context.querySelector('input[type="file"]').files[0];
                                convertToBase64(file, $(this).closest('td').find('img'));
                                $(this).find('input').val("");
                            }
                        } else if ($(this).closest('td').find('.form-display-element').hasClass("textArea")) {
                            $(this).closest('td').find('textarea').val($(this).closest('td').find('.form-edit-element textarea').val());
                        } else if (!$(this).find('input').hasClass('js-switch-small')) {
                            $(this).closest('td').find('.form-display-element').html($(this).find('input').val());
                        }
                    }
                });

                form.find('.form-display-element').css('display', 'block');
                form.find('.form-edit-element').css('display', 'none');
                location.reload();
            }
            else {
                $("#errorModalMessage").html(data.Error);
                $("#errorModal").modal('show');
            }
        }).fail(function () {
            submitIcon.removeClass('fa fa-spinner fa-spin');
            $("#errorModalMessage").html(data.Error);
            $("#errorModal").modal('show');
        });
    });

    var url = new URL(window.location.href);
    var enterGoogleApiKey = decodeURI(url.searchParams.get("enterGoogleApiKey"));
    if (enterGoogleApiKey === "True" || enterGoogleApiKey === true) {
        $("#GoogleApiKey").focus();
    }
}

function openServerDataModal($fiscalServer, $fiscalTaxServer, $fiscalCheckConnectionServer, title, tableTitles, rowTitles) {
    let serverLines = "<tr><td class='nowrap-text no-padding-bottom'>" + rowTitles[0] + "</td><td class='no-padding'><input id='fiscalServer_dataModal' class='form-control' value='" + $fiscalServer.val() + "' /></td></tr>";
    serverLines += "<tr><td class='nowrap-text no-padding-bottom'>" + rowTitles[1] + "</td><td class='no-padding'><input id='fiscalTaxServer_dataModal' class='form-control' value='" + $fiscalTaxServer.val() + "' /></td></tr>";
    serverLines += "<tr><td class='nowrap-text no-padding-bottom'>" + rowTitles[2] + "</td><td class='no-padding'><input id='fiscalCheckConnectionServer_dataModal' class='form-control' value='" + $fiscalCheckConnectionServer.val() + "' /></td></tr>";

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "modal",
        title: title,
        content: "<table class='table table-bordered'><thead><tr><th width='20%'>" + tableTitles[0] + "</th><th width='80%'>" + tableTitles[1] + "</th></tr></thead><tbody>" + serverLines + "<tbody></table>",
        buttons: [
            {
                text: $("#OkLoc").val(),
                icon: 'fa fa-check',
                type: 'primary',
                closeOnAction: true,
                action: function () {
                    $fiscalServer.val($("#fiscalServer_dataModal").val());
                    $fiscalTaxServer.val($("#fiscalTaxServer_dataModal").val());
                    $fiscalCheckConnectionServer.val($("#fiscalCheckConnectionServer_dataModal").val());
                    $fiscalServer.closest("form").find(".buttons-tabbed button[type='submit']").click();
                }
            }
        ]
    });
}

function openFiscalDateModal($fiscalDate, $fiscalDateNew, title, tableTitles, rowTitles) {
    var dateNewVal = $fiscalDateNew.val();
    let tableRows = "<tr><td class='no-padding'><input id='fiscalDate_dataModal' class='form-control datepicker'" + (dateNewVal.length > 0 ? " disabled" : "") + " value='" + $fiscalDate.val() + "' /></td><td class='nowrap-text disabled-col'>" + rowTitles[0] + "</td></tr>";
    tableRows += "<tr><td class='no-padding'><input id='fiscalDateNew_dataModal' class='form-control datepicker' value='" + dateNewVal + "' /></td><td class='nowrap-text disabled-col '>" + rowTitles[1] + "</td></tr>";

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "modal",
        title: title,
        width: "20%",
        minWidth: "400px",
        id: "fiscalDateModal",
        onOpen: function () {
            $('#fiscalDateModal').find(".datepicker").datepicker({
                format: 'dd.mm.yyyy',
                language: $('#siteLocale').val()
            }).on('changeDate', function () {
                $(this).datepicker('hide');
            });
        },
        content: "<table class='table table-bordered'><thead><tr><th width='50%'>" + tableTitles[0] + "</th><th width='50%'>" + tableTitles[1] + "</th></tr></thead><tbody>" + tableRows + "<tbody></table>",
        buttons: [
            {
                text: $("#OkLoc").val(),
                icon: 'fa fa-check',
                type: 'primary',
                closeOnAction: true,
                action: function () {
                    console.log($fiscalDate, $fiscalDate.closest("form"));
                    $fiscalDate.val($("#fiscalDate_dataModal").val());
                    $fiscalDateNew.val($("#fiscalDateNew_dataModal").val());
                    $fiscalDate.closest("form").find(".buttons-tabbed button[type='submit']").click();
                }
            }
        ]
    });
}

function checkFiscalServerConnectivity() {
    $("#checkFiscalServerConnectivityBtn").find("i").removeClass("fa-wifi").addClass("fa-spinner fa-spin");

    $.post($("#UrlCheckFiscalServiceConnectivity").val(), {
        FiscalServer: $("#FiscalServer").val()
    }).done(function (isServiceAvailable) {
        if (isServiceAvailable) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "success",
                text: $("#ConnectionCheckSuccessLoc").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#OkLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
        else {
            showError($("#ConnectionCheckFailedLoc").val());
        }
        $("#checkFiscalServerConnectivityBtn").find("i").addClass("fa-wifi").removeClass("fa-spinner fa-spin");
    }).fail(function () {
        showError($("#ErrorHappenedWhileCheckingFiscalServiceConnectivityLoc").val());
        $("#checkFiscalServerConnectivityBtn").find("i").addClass("fa-wifi").removeClass("fa-spinner fa-spin");
    });
}


function showError(text) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "error",
        text: text,
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#OkLoc").val(),
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function convertToBase64(file, element) {
    var reader = new FileReader();
    reader.onload = function () {
        var img = new Image;
        img.onload = function () {
            element.attr('src', reader.result);
            element.css((img.width > img.height ? 'max-width' : 'max-height'), '300px').css((img.width > img.height ? 'max-height' : 'max-width'), 'none');
        };

        img.src = reader.result;
    };

    reader.readAsDataURL(file);
}

function dropifyUpload() {
    $('.dropify').dropify({
        messages: {
            'default': $("#DragAndDropOrClick").val(),
            'replace': $("#DragAndDropOrClick").val(),
            'remove': $("#Remove").val(),
            'error': $("#GeneralErrorMessage").val()
        },
        error: {
            'imageFormat': $("#WrongImageFormat").val()
        }
    });
}