/*
This file is part of SystemTestPortal.
Copyright (C) 2017  Institute of Software Technology, University of Stuttgart

SystemTestPortal is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SystemTestPortal is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with SystemTestPortal.  If not, see <http://www.gnu.org/licenses/>.
*/

/* attach a handler to the form submit button */
$("#signin").submit(function (event) {

    /* stop form from submitting normally */
    event.preventDefault();

    /* get the action attribute from the <form action=""> element */
    var $form = $( this );
    var url = $form.attr( 'action' );

    /* Send sign-in request */
    var posting = $.post( url, {
        inputPassword: $('#inputPassword').val(),
        inputIdentifier: $('#inputEmail').val()
    } );

    posting.done(function () {
        $('#signin-modal').modal('hide');
        location.reload();
    }).fail(function (response) {
        if (response.status >= 500) {
            $('#signin-modal').modal('hide');
            $( "#modalPlaceholder" ).empty().append(response.responseText);
            $('#errorModal').modal('show');
        } else {
            $('#passwordFeedback').text(response.responseText);
            $('#formEmail').addClass('has-danger');
            $('#formPassword').addClass('has-danger');
        }
    });
});

$('#signin-modal').on('shown.bs.modal', function () {
    $('#inputEmail').focus();
});

// Clears errors when sign-in modal is closed
$('#signin-modal').on('hidden.bs.modal', function () {
    clearErrors()
});

// Clears errors displayed in the sign-in modal
function clearErrors() {
    $('#passwordFeedback').text("");
    $('#formEmail').removeClass('has-danger');
    $('#formPassword').removeClass('has-danger');
}