@model PantheonRA.BackOffice.Models.LoginViewModel

@{
    Layout = "~/Views/Shared/_LoginLayout.cshtml";
}

<div class="login-splash">
    @*TODO: localize link*@
    <a href="https://www.datalab.si/" target="_blank" class="login-splash-logo"></a>
</div>
<div class="login animated fadeInDown">
    <div class="login-logo"></div>
    @Html.Partial("_PartnerIcon", "Account")

    <div class="login-title">@Html.Raw(string.Format(Loc.LoginTitle, "<br/>"))</div>

    <div class="login-form loginscreen">
        <div>
            @using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @class = "m-t", @id = "login-form" }))
            {
                @Html.HiddenFor(loginModel => loginModel.ReturnUrl)

                <div class="form-group">
                    <label>@Loc.User</label>
                    @Html.TextBoxFor(loginModel => loginModel.Username, new { @class = "form-control" })
                    @Html.ValidationMessageFor(loginModel => loginModel.Username)
                </div>

                <div class="form-group">
                    <label>@Loc.Password</label>
                    @Html.PasswordFor(loginModel => loginModel.Password, new { @class = "form-control", @type = "password" })
                    @Html.ValidationMessageFor(loginModel => loginModel.Password)
                </div>

                <div class="form-group">
                    <label>@Loc.Company</label>
                    @Html.TextBoxFor(loginModel => loginModel.DomainName, new { @class = "form-control" })
                    @Html.ValidationMessageFor(loginModel => loginModel.DomainName)
                </div>

                @Html.ValidationMessage("", new { @class = "text-danger m-b-xs" })

                <button type="submit" class="btn btn-success block m-b form-submit">
                    <i class="fa fa-spin fa-spinner hidden"></i><span>@Loc.Login</span>
                </button>

                <div class="login-links">
                    @if (Request.ApplicationPath != "/demo")
                    {
                        <a href="#" onclick="forgotPassword();" id="forgot-password">@Loc.DidYouForgotPassword</a><br />
                    }
                    <a href="@Loc.PersonalProtectionPolicyUrl" target="_blank">@Loc.PersonalProtectionPolicy</a><br />
                    <a href="@Loc.DatalabPantheonTermsOfUseUrl" target="_blank">@Loc.DatalabPantheonTermsOfUse</a>

                    <p class="m-t-xs login-copyright">Copyright Datalab &copy; 1997 - @DateTime.Now.Year</p>
                </div>
            }
        </div>
    </div>
</div>
<div class="browser-message">
    <div class="browser-message-content">
        <img class="browser-message-icon" src="~/Content/Images/chrome-logo.svg" />
        <div class="m-b-md">@Loc.UnsupportedBrowserMessage</div>
        <div>@Html.Raw(string.Format(Loc.InstallRequredBrowser, "https://support.google.com/chrome/answer/95346"))</div>
        <button onclick="$(this).closest('.browser-message').hide()" class="m-t-md btn btn-default browser-message-continue-button">@Loc.ContinueAnyways</button>
    </div>
    <a href="https://www.datalab.si/" target="_blank"><img class="browser-message-logo" src="~/Content/Images/datalab_logo_dark.svg" /></a>
</div>

@Html.Partial("_GDPRNotice", "Account")
@Html.Partial("_ChangePassword", "Account")
@Html.Partial("_DatabaseUpdateNotice", "Account")
@{Html.RenderPartial("~/Views/Shared/Components/_LicencingModals.cshtml");}

<script src="~/Scripts/inspinia/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
@Scripts.Render("~/bundles/browserChecker")
@Scripts.Render("~/bundles/login")
@Scripts.Render("~/bundles/lpfr")

<script type="text/javascript">
    var loginChecked = false;

    $(document).ready(function () {
        clearLastDocumentType();
        window.localStorage.setItem('AnnouncmentDataFetched', false);

        var headers = "@Request.Headers["LicenceError"]";
        if (headers === "1") {

            @{
                var licCount = 0;
                var licUsers = "";
            }

            @{
                if (Request.Headers["LicenceError"] != null && Request.Headers["LicenceError"].ToString() == "1")
                {
                    licCount = PantheonRA.BackOffice.Licensing.DomainLicences(Request.Headers["LicenceDomain"].ToString()).LicTotal();
                    licUsers = String.Join(", ", PantheonRA.BackOffice.Licensing.DomainLicences(Request.Headers["LicenceDomain"].ToString()).LicUsernames());
                }
            }

            var licTotal = @licCount;
            var licUsernames = "@licUsers";

            $("#loginLicenceErrorMessage").text(stringFormat("@Loc.LoginDeniedExceededNumberOfLicences", licTotal));
            $("#loginLicenceUsersErrorMessage").text(stringFormat("@Loc.CurrentlyLoggedInUsers", licTotal) + " " + licUsernames);
            $("#loginLicenceErrorModal").modal("show");
        }

        $(".browser-message").browserCheck(["Chrome"]);
        if('@Request.ApplicationPath' !== '/demo')
            $("#DomainName").val(localStorage.getItem('LastCompany'));

        if('@Request.ApplicationPath' !== '/' && '@Request.ApplicationPath' !== '/demo')
            openDatabaseUpdateModal();

        window.localStorage.setItem('DisplayPopup', true);
        window.localStorage.setItem('AnnouncementsCount', null);

        $('.input-validation-error').parents('.form-group').addClass('has-error');

        if ('@Model.Blockade' === '@Boolean.TrueString') {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                help: '@SiteHelpAttributeHelper.GetHelpUrl(PantheonRA.BackOffice.Enums.HelpIds.Blocade)',
                type: "error",
                text: '@Html.Raw(string.Format(Loc.LoginBlocked, Loc.BlueNumber).Replace("'", "´"))',
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: '@Loc.Confirm',
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }

        $('#login-form').submit(function (e) {
            localStorage.setItem('LastCompany', $("#DomainName").val());
            localStorage.removeItem("NewTimeRecordFilter");

            if (!$("#ReturnUrl").val()) {
                $("#ReturnUrl").val(localStorage.getItem('LastPage' + $("#DomainName").val().trim() + "_" + $("#Username").val().trim()));
            }

            $("button[type='submit']").attr("disabled", true);
            $("button[type='submit'] i").removeClass("hidden");

            if (loginChecked) return;

            e.preventDefault();

            loginChecked = true; //TODO: remove when GDPR check is implemented
            $('#login-form').submit(); //TODO: remove when GDPR check is implemented

            @*$.get("@Url.Action("GetDomainLicense", "Account")?domainName=" + $("#DomainName").val(), function (response) {
                console.log("GetDomainLicense", response);
            });*@

            @*let form = $(this);
            $.post('@Url.Action("CheckGDPR")', form.serialize()).done(function (data) {

                if (data.UserLogin) {
                    $("button[type='submit'] i").addClass("fa-lock").removeClass("fa-spin fa-spinner");

                    if (!data.GDPRConfirmed) {
                        openGDPRNoticeModal(form.find('#DomainName').val(), form.find('#Username').val());
                    }
                    else {
                        checkPasswordChange();
                    }
                }
                else {
                    loginChecked = true;
                    $('#login-form').submit();
                }
            }).fail(function () {
                loginChecked = true;
                $('#login-form').submit();
                $("button[type='submit'] i").addClass("fa-lock").removeClass("fa-spin fa-spinner");
            });*@
        });

        $('#GDPR-form').on('GDPRNoticeDone', function () {
            checkPasswordChange();
        });

        $('#password-change-form').on('passwordChangeDone', function (e, passwordChanged) {
            if (passwordChanged) {
                loginChecked = true;
                $('#login-form #Password').val($('#password-change-form #NewPassword').val());
            }

            $('#login-form').submit();
            $('#loginButtonIcon').addClass('fa fa-spinner fa-spin fa-lg fa-fw');
        });


        function checkPasswordChange() {
            var form = $('#login-form');

            $('#loginButtonIcon').addClass('fa fa-spinner fa-spin fa-lg fa-fw');
            $.post('@Url.Action("CheckPasswordChange")', form.serialize()).done(function (data) {

                if (data.ChangePasswordRequired) {
                    $('#loginButtonIcon').removeClass('fa fa-spinner fa-spin fa-lg fa-fw');
                    openChangePasswordModal(form.find('#DomainName').val(), form.find('#Username').val(), true, data.User.DisplayName + ' (' + data.User.Username + ')', false, data.serialNumberRequired);
                }
                else {
                    loginChecked = true;
                    form.submit();
                }
            }).fail(function () {
                $('#loginButtonIcon').removeClass('fa fa-spinner fa-spin fa-lg fa-fw');
            });
        }
    });

    function forgotPassword() {
        var username = $("#Username").val();
        var domainName = $("#DomainName").val();
        var url = '@Url.Action("ForgotPassword", "Account")';
        window.location.href = url + "?userName=" + username + "&domainName=" + domainName;
    }

    function openLoginLicenceHelp() {
        window.open('@Loc.LoginExceededLicencesHelpUrl', '_blank');
    }

    function buyLicences() {
        window.open('@Loc.ContactSupportUrl', '_blank');
    }
</script>